@workos-inc/node 7.9.0 → 7.11.0

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 (34) hide show
  1. package/README.md +4 -0
  2. package/lib/common/crypto/crypto-provider.d.ts +32 -0
  3. package/lib/common/crypto/crypto-provider.js +13 -0
  4. package/lib/common/crypto/node-crypto-provider.d.ts +12 -0
  5. package/lib/common/crypto/node-crypto-provider.js +73 -0
  6. package/lib/common/crypto/subtle-crypto-provider.d.ts +15 -0
  7. package/lib/common/crypto/subtle-crypto-provider.js +75 -0
  8. package/lib/common/interfaces/http-client.interface.d.ts +20 -0
  9. package/lib/common/interfaces/http-client.interface.js +2 -0
  10. package/lib/common/interfaces/index.d.ts +1 -0
  11. package/lib/common/interfaces/index.js +1 -0
  12. package/lib/common/interfaces/workos-options.interface.d.ts +1 -0
  13. package/lib/common/net/fetch-client.d.ts +22 -0
  14. package/lib/common/net/fetch-client.js +112 -0
  15. package/lib/common/net/http-client.d.ts +39 -0
  16. package/lib/common/net/http-client.js +76 -0
  17. package/lib/common/net/node-client.d.ts +23 -0
  18. package/lib/common/net/node-client.js +155 -0
  19. package/lib/index.d.ts +10 -2
  20. package/lib/index.js +31 -3
  21. package/lib/index.worker.d.ts +23 -0
  22. package/lib/index.worker.js +46 -0
  23. package/lib/organizations/interfaces/create-organization-options.interface.d.ts +8 -2
  24. package/lib/organizations/interfaces/update-organization-options.interface.d.ts +8 -2
  25. package/lib/user-management/user-management.js +13 -1
  26. package/lib/webhooks/webhooks.d.ts +3 -2
  27. package/lib/webhooks/webhooks.js +5 -37
  28. package/lib/webhooks/webhooks.spec.js +30 -0
  29. package/lib/workos.d.ts +5 -2
  30. package/lib/workos.js +28 -14
  31. package/lib/workos.spec.js +85 -20
  32. package/package.json +12 -5
  33. package/lib/common/utils/fetch-client.d.ts +0 -31
  34. package/lib/common/utils/fetch-client.js +0 -108
@@ -0,0 +1,155 @@
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.NodeHttpClientResponse = exports.NodeHttpClient = void 0;
36
+ const http_client_1 = require("./http-client");
37
+ const http_ = __importStar(require("node:http"));
38
+ const https_ = __importStar(require("node:https"));
39
+ // `import * as http_ from 'http'` creates a "Module Namespace Exotic Object"
40
+ // which is immune to monkey-patching, whereas http_.default (in an ES Module context)
41
+ // will resolve to the same thing as require('http'), which is
42
+ // monkey-patchable. We care about this because users in their test
43
+ // suites might be using a library like "nock" which relies on the ability
44
+ // to monkey-patch and intercept calls to http.request.
45
+ const http = http_.default || http_;
46
+ const https = https_.default || https_;
47
+ class NodeHttpClient extends http_client_1.HttpClient {
48
+ constructor(baseURL, options) {
49
+ super(baseURL, options);
50
+ this.baseURL = baseURL;
51
+ this.options = options;
52
+ this.httpAgent = new http.Agent({ keepAlive: true });
53
+ this.httpsAgent = new https.Agent({ keepAlive: true });
54
+ }
55
+ getClientName() {
56
+ return 'node';
57
+ }
58
+ get(path, options) {
59
+ return __awaiter(this, void 0, void 0, function* () {
60
+ const resourceURL = http_client_1.HttpClient.getResourceURL(this.baseURL, path, options.params);
61
+ return yield this.nodeRequest(resourceURL, 'GET', null, options.headers);
62
+ });
63
+ }
64
+ post(path, entity, options) {
65
+ return __awaiter(this, void 0, void 0, function* () {
66
+ const resourceURL = http_client_1.HttpClient.getResourceURL(this.baseURL, path, options.params);
67
+ return yield this.nodeRequest(resourceURL, 'POST', http_client_1.HttpClient.getBody(entity), Object.assign(Object.assign({}, http_client_1.HttpClient.getContentTypeHeader(entity)), options.headers));
68
+ });
69
+ }
70
+ put(path, entity, options) {
71
+ return __awaiter(this, void 0, void 0, function* () {
72
+ const resourceURL = http_client_1.HttpClient.getResourceURL(this.baseURL, path, options.params);
73
+ return yield this.nodeRequest(resourceURL, 'PUT', http_client_1.HttpClient.getBody(entity), Object.assign(Object.assign({}, http_client_1.HttpClient.getContentTypeHeader(entity)), options.headers));
74
+ });
75
+ }
76
+ delete(path, options) {
77
+ return __awaiter(this, void 0, void 0, function* () {
78
+ const resourceURL = http_client_1.HttpClient.getResourceURL(this.baseURL, path, options.params);
79
+ return yield this.nodeRequest(resourceURL, 'DELETE', null, options.headers);
80
+ });
81
+ }
82
+ nodeRequest(url, method, body, headers) {
83
+ return __awaiter(this, void 0, void 0, function* () {
84
+ return new Promise((resolve, reject) => {
85
+ var _a, _b;
86
+ const isSecureConnection = url.startsWith('https');
87
+ const agent = isSecureConnection ? this.httpsAgent : this.httpAgent;
88
+ const lib = isSecureConnection ? https : http;
89
+ const { 'User-Agent': userAgent } = (_a = this.options) === null || _a === void 0 ? void 0 : _a.headers;
90
+ const options = {
91
+ method,
92
+ headers: Object.assign(Object.assign(Object.assign({ Accept: 'application/json, text/plain, */*', 'Content-Type': 'application/json' }, (_b = this.options) === null || _b === void 0 ? void 0 : _b.headers), headers), { 'User-Agent': this.addClientToUserAgent(userAgent.toString()) }),
93
+ agent,
94
+ };
95
+ const req = lib.request(url, options, (res) => __awaiter(this, void 0, void 0, function* () {
96
+ const clientResponse = new NodeHttpClientResponse(res);
97
+ if (res.statusCode && (res.statusCode < 200 || res.statusCode > 299)) {
98
+ reject(new http_client_1.HttpClientError({
99
+ message: res.statusMessage,
100
+ response: {
101
+ status: res.statusCode,
102
+ headers: res.headers,
103
+ data: yield clientResponse.toJSON(),
104
+ },
105
+ }));
106
+ }
107
+ resolve(clientResponse);
108
+ }));
109
+ req.on('error', (err) => {
110
+ reject(new Error(err.message));
111
+ });
112
+ if (body) {
113
+ req.setHeader('Content-Length', Buffer.byteLength(body));
114
+ req.write(body);
115
+ }
116
+ req.end();
117
+ });
118
+ });
119
+ }
120
+ }
121
+ exports.NodeHttpClient = NodeHttpClient;
122
+ // tslint:disable-next-line
123
+ class NodeHttpClientResponse extends http_client_1.HttpClientResponse {
124
+ constructor(res) {
125
+ // @ts-ignore
126
+ super(res.statusCode, res.headers || {});
127
+ this._res = res;
128
+ }
129
+ getRawResponse() {
130
+ return this._res;
131
+ }
132
+ toJSON() {
133
+ return new Promise((resolve, reject) => {
134
+ const contentType = this._res.headers['content-type'];
135
+ const isJsonResponse = contentType === null || contentType === void 0 ? void 0 : contentType.includes('application/json');
136
+ if (!isJsonResponse) {
137
+ resolve(null);
138
+ }
139
+ let response = '';
140
+ this._res.setEncoding('utf8');
141
+ this._res.on('data', (chunk) => {
142
+ response += chunk;
143
+ });
144
+ this._res.once('end', () => {
145
+ try {
146
+ resolve(JSON.parse(response));
147
+ }
148
+ catch (e) {
149
+ reject(e);
150
+ }
151
+ });
152
+ });
153
+ }
154
+ }
155
+ exports.NodeHttpClientResponse = NodeHttpClientResponse;
package/lib/index.d.ts CHANGED
@@ -1,4 +1,7 @@
1
+ import { HttpClient } from './common/net/http-client';
2
+ import { Webhooks } from './webhooks/webhooks';
1
3
  import { WorkOS } from './workos';
4
+ import { WorkOSOptions } from './common/interfaces';
2
5
  export * from './audit-logs/interfaces';
3
6
  export * from './common/exceptions';
4
7
  export * from './common/interfaces';
@@ -11,5 +14,10 @@ export * from './passwordless/interfaces';
11
14
  export * from './portal/interfaces';
12
15
  export * from './sso/interfaces';
13
16
  export * from './user-management/interfaces';
14
- export { WorkOS };
15
- export default WorkOS;
17
+ declare class WorkOSNode extends WorkOS {
18
+ /** @override */
19
+ createHttpClient(options: WorkOSOptions, userAgent: string): HttpClient;
20
+ /** @override */
21
+ createWebhookClient(): Webhooks;
22
+ }
23
+ export { WorkOSNode as WorkOS };
package/lib/index.js CHANGED
@@ -15,8 +15,12 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  exports.WorkOS = void 0;
18
+ const node_crypto_provider_1 = require("./common/crypto/node-crypto-provider");
19
+ const subtle_crypto_provider_1 = require("./common/crypto/subtle-crypto-provider");
20
+ const fetch_client_1 = require("./common/net/fetch-client");
21
+ const node_client_1 = require("./common/net/node-client");
22
+ const webhooks_1 = require("./webhooks/webhooks");
18
23
  const workos_1 = require("./workos");
19
- Object.defineProperty(exports, "WorkOS", { enumerable: true, get: function () { return workos_1.WorkOS; } });
20
24
  __exportStar(require("./audit-logs/interfaces"), exports);
21
25
  __exportStar(require("./common/exceptions"), exports);
22
26
  __exportStar(require("./common/interfaces"), exports);
@@ -29,5 +33,29 @@ __exportStar(require("./passwordless/interfaces"), exports);
29
33
  __exportStar(require("./portal/interfaces"), exports);
30
34
  __exportStar(require("./sso/interfaces"), exports);
31
35
  __exportStar(require("./user-management/interfaces"), exports);
32
- // tslint:disable-next-line:no-default-export
33
- exports.default = workos_1.WorkOS;
36
+ class WorkOSNode extends workos_1.WorkOS {
37
+ /** @override */
38
+ createHttpClient(options, userAgent) {
39
+ var _a;
40
+ const opts = Object.assign(Object.assign({}, options.config), { headers: Object.assign(Object.assign({}, (_a = options.config) === null || _a === void 0 ? void 0 : _a.headers), { Authorization: `Bearer ${this.key}`, 'User-Agent': userAgent }) });
41
+ if (typeof fetch !== 'undefined' ||
42
+ typeof options.fetchFn !== 'undefined') {
43
+ return new fetch_client_1.FetchHttpClient(this.baseURL, opts, options.fetchFn);
44
+ }
45
+ else {
46
+ return new node_client_1.NodeHttpClient(this.baseURL, opts);
47
+ }
48
+ }
49
+ /** @override */
50
+ createWebhookClient() {
51
+ let cryptoProvider;
52
+ if (typeof crypto !== 'undefined' && typeof crypto.subtle !== 'undefined') {
53
+ cryptoProvider = new subtle_crypto_provider_1.SubtleCryptoProvider();
54
+ }
55
+ else {
56
+ cryptoProvider = new node_crypto_provider_1.NodeCryptoProvider();
57
+ }
58
+ return new webhooks_1.Webhooks(cryptoProvider);
59
+ }
60
+ }
61
+ exports.WorkOS = WorkOSNode;
@@ -0,0 +1,23 @@
1
+ import { HttpClient } from './common/net/http-client';
2
+ import { WorkOSOptions } from './index.worker';
3
+ import { Webhooks } from './webhooks/webhooks';
4
+ import { WorkOS } from './workos';
5
+ export * from './audit-logs/interfaces';
6
+ export * from './common/exceptions';
7
+ export * from './common/interfaces';
8
+ export * from './common/utils/pagination';
9
+ export * from './directory-sync/interfaces';
10
+ export * from './directory-sync/utils/get-primary-email';
11
+ export * from './events/interfaces';
12
+ export * from './organizations/interfaces';
13
+ export * from './passwordless/interfaces';
14
+ export * from './portal/interfaces';
15
+ export * from './sso/interfaces';
16
+ export * from './user-management/interfaces';
17
+ declare class WorkOSWorker extends WorkOS {
18
+ /** @override */
19
+ createHttpClient(options: WorkOSOptions, userAgent: string): HttpClient;
20
+ /** @override */
21
+ createWebhookClient(): Webhooks;
22
+ }
23
+ export { WorkOSWorker as WorkOS };
@@ -0,0 +1,46 @@
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 __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.WorkOS = void 0;
18
+ const subtle_crypto_provider_1 = require("./common/crypto/subtle-crypto-provider");
19
+ const fetch_client_1 = require("./common/net/fetch-client");
20
+ const webhooks_1 = require("./webhooks/webhooks");
21
+ const workos_1 = require("./workos");
22
+ __exportStar(require("./audit-logs/interfaces"), exports);
23
+ __exportStar(require("./common/exceptions"), exports);
24
+ __exportStar(require("./common/interfaces"), exports);
25
+ __exportStar(require("./common/utils/pagination"), exports);
26
+ __exportStar(require("./directory-sync/interfaces"), exports);
27
+ __exportStar(require("./directory-sync/utils/get-primary-email"), exports);
28
+ __exportStar(require("./events/interfaces"), exports);
29
+ __exportStar(require("./organizations/interfaces"), exports);
30
+ __exportStar(require("./passwordless/interfaces"), exports);
31
+ __exportStar(require("./portal/interfaces"), exports);
32
+ __exportStar(require("./sso/interfaces"), exports);
33
+ __exportStar(require("./user-management/interfaces"), exports);
34
+ class WorkOSWorker extends workos_1.WorkOS {
35
+ /** @override */
36
+ createHttpClient(options, userAgent) {
37
+ var _a;
38
+ return new fetch_client_1.FetchHttpClient(this.baseURL, Object.assign(Object.assign({}, options.config), { headers: Object.assign(Object.assign({}, (_a = options.config) === null || _a === void 0 ? void 0 : _a.headers), { Authorization: `Bearer ${this.key}`, 'User-Agent': userAgent }) }));
39
+ }
40
+ /** @override */
41
+ createWebhookClient() {
42
+ const cryptoProvider = new subtle_crypto_provider_1.SubtleCryptoProvider();
43
+ return new webhooks_1.Webhooks(cryptoProvider);
44
+ }
45
+ }
46
+ exports.WorkOS = WorkOSWorker;
@@ -2,8 +2,11 @@ import { PostOptions } from '../../common/interfaces';
2
2
  import { DomainData } from './domain-data.interface';
3
3
  export interface CreateOrganizationOptions {
4
4
  name: string;
5
- allowProfilesOutsideOrganization?: boolean;
6
5
  domainData?: DomainData[];
6
+ /**
7
+ * @deprecated If you need to allow sign-ins from any email domain, contact support@workos.com.
8
+ */
9
+ allowProfilesOutsideOrganization?: boolean;
7
10
  /**
8
11
  * @deprecated Use `domain_data` instead.
9
12
  */
@@ -11,8 +14,11 @@ export interface CreateOrganizationOptions {
11
14
  }
12
15
  export interface SerializedCreateOrganizationOptions {
13
16
  name: string;
14
- allow_profiles_outside_organization?: boolean;
15
17
  domain_data?: DomainData[];
18
+ /**
19
+ * @deprecated If you need to allow sign-ins from any email domain, contact support@workos.com.
20
+ */
21
+ allow_profiles_outside_organization?: boolean;
16
22
  /**
17
23
  * @deprecated Use `domain_data` instead.
18
24
  */
@@ -2,8 +2,11 @@ import { DomainData } from './domain-data.interface';
2
2
  export interface UpdateOrganizationOptions {
3
3
  organization: string;
4
4
  name: string;
5
- allowProfilesOutsideOrganization?: boolean;
6
5
  domainData?: DomainData[];
6
+ /**
7
+ * @deprecated If you need to allow sign-ins from any email domain, contact support@workos.com.
8
+ */
9
+ allowProfilesOutsideOrganization?: boolean;
7
10
  /**
8
11
  * @deprecated Use `domain_data` instead.
9
12
  */
@@ -11,8 +14,11 @@ export interface UpdateOrganizationOptions {
11
14
  }
12
15
  export interface SerializedUpdateOrganizationOptions {
13
16
  name: string;
14
- allow_profiles_outside_organization?: boolean;
15
17
  domain_data?: DomainData[];
18
+ /**
19
+ * @deprecated If you need to allow sign-ins from any email domain, contact support@workos.com.
20
+ */
21
+ allow_profiles_outside_organization?: boolean;
16
22
  /**
17
23
  * @deprecated Use `domain_data` instead.
18
24
  */
@@ -8,6 +8,17 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  step((generator = generator.apply(thisArg, _arguments || [])).next());
9
9
  });
10
10
  };
11
+ var __rest = (this && this.__rest) || function (s, e) {
12
+ var t = {};
13
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
14
+ t[p] = s[p];
15
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
16
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
17
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
18
+ t[p[i]] = s[p[i]];
19
+ }
20
+ return t;
21
+ };
11
22
  Object.defineProperty(exports, "__esModule", { value: true });
12
23
  exports.UserManagement = void 0;
13
24
  const pagination_1 = require("../common/utils/pagination");
@@ -183,7 +194,8 @@ class UserManagement {
183
194
  }
184
195
  listAuthFactors(options) {
185
196
  return __awaiter(this, void 0, void 0, function* () {
186
- return new pagination_1.AutoPaginatable(yield (0, fetch_and_deserialize_1.fetchAndDeserialize)(this.workos, `/user_management/users/${options.userId}/auth_factors`, factor_serializer_1.deserializeFactor, options), (params) => (0, fetch_and_deserialize_1.fetchAndDeserialize)(this.workos, `/user_management/users/${options.userId}/auth_factors`, factor_serializer_1.deserializeFactor, params), options);
197
+ const { userId } = options, restOfOptions = __rest(options, ["userId"]);
198
+ return new pagination_1.AutoPaginatable(yield (0, fetch_and_deserialize_1.fetchAndDeserialize)(this.workos, `/user_management/users/${userId}/auth_factors`, factor_serializer_1.deserializeFactor, restOfOptions), (params) => (0, fetch_and_deserialize_1.fetchAndDeserialize)(this.workos, `/user_management/users/${userId}/auth_factors`, factor_serializer_1.deserializeFactor, params), restOfOptions);
187
199
  });
188
200
  }
189
201
  deleteUser(userId) {
@@ -1,6 +1,8 @@
1
1
  import { Event } from '../common/interfaces';
2
+ import { CryptoProvider } from '../common/crypto/crypto-provider';
2
3
  export declare class Webhooks {
3
- private encoder;
4
+ private cryptoProvider;
5
+ constructor(cryptoProvider: CryptoProvider);
4
6
  constructEvent({ payload, sigHeader, secret, tolerance, }: {
5
7
  payload: unknown;
6
8
  sigHeader: string;
@@ -15,5 +17,4 @@ export declare class Webhooks {
15
17
  }): Promise<boolean>;
16
18
  getTimestampAndSignatureHash(sigHeader: string): [string, string];
17
19
  computeSignature(timestamp: any, payload: any, secret: string): Promise<string>;
18
- secureCompare(stringA: string, stringB: string): Promise<boolean>;
19
20
  }
@@ -13,8 +13,8 @@ exports.Webhooks = void 0;
13
13
  const exceptions_1 = require("../common/exceptions");
14
14
  const serializers_1 = require("../common/serializers");
15
15
  class Webhooks {
16
- constructor() {
17
- this.encoder = new TextEncoder();
16
+ constructor(cryptoProvider) {
17
+ this.cryptoProvider = cryptoProvider;
18
18
  }
19
19
  constructEvent({ payload, sigHeader, secret, tolerance = 180000, }) {
20
20
  return __awaiter(this, void 0, void 0, function* () {
@@ -34,7 +34,8 @@ class Webhooks {
34
34
  throw new exceptions_1.SignatureVerificationException('Timestamp outside the tolerance zone');
35
35
  }
36
36
  const expectedSig = yield this.computeSignature(timestamp, payload, secret);
37
- if ((yield this.secureCompare(expectedSig, signatureHash)) === false) {
37
+ if ((yield this.cryptoProvider.secureCompare(expectedSig, signatureHash)) ===
38
+ false) {
38
39
  throw new exceptions_1.SignatureVerificationException('Signature hash does not match the expected signature hash for payload');
39
40
  }
40
41
  return true;
@@ -54,41 +55,8 @@ class Webhooks {
54
55
  return __awaiter(this, void 0, void 0, function* () {
55
56
  payload = JSON.stringify(payload);
56
57
  const signedPayload = `${timestamp}.${payload}`;
57
- const key = yield crypto.subtle.importKey('raw', this.encoder.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
58
- const signatureBuffer = yield crypto.subtle.sign('HMAC', key, this.encoder.encode(signedPayload));
59
- // crypto.subtle returns the signature in base64 format. This must be
60
- // encoded in hex to match the CryptoProvider contract. We map each byte in
61
- // the buffer to its corresponding hex octet and then combine into a string.
62
- const signatureBytes = new Uint8Array(signatureBuffer);
63
- const signatureHexCodes = new Array(signatureBytes.length);
64
- for (let i = 0; i < signatureBytes.length; i++) {
65
- signatureHexCodes[i] = byteHexMapping[signatureBytes[i]];
66
- }
67
- return signatureHexCodes.join('');
68
- });
69
- }
70
- secureCompare(stringA, stringB) {
71
- return __awaiter(this, void 0, void 0, function* () {
72
- const bufferA = this.encoder.encode(stringA);
73
- const bufferB = this.encoder.encode(stringB);
74
- if (bufferA.length !== bufferB.length) {
75
- return false;
76
- }
77
- const algorithm = { name: 'HMAC', hash: 'SHA-256' };
78
- const key = (yield crypto.subtle.generateKey(algorithm, false, [
79
- 'sign',
80
- 'verify',
81
- ]));
82
- const hmac = yield crypto.subtle.sign(algorithm, key, bufferA);
83
- const equal = yield crypto.subtle.verify(algorithm, key, hmac, bufferB);
84
- return equal;
58
+ return yield this.cryptoProvider.computeHMACSignatureAsync(signedPayload, secret);
85
59
  });
86
60
  }
87
61
  }
88
62
  exports.Webhooks = Webhooks;
89
- // Cached mapping of byte to hex representation. We do this once to avoid re-
90
- // computing every time we need to convert the result of a signature to hex.
91
- const byteHexMapping = new Array(256);
92
- for (let i = 0; i < byteHexMapping.length; i++) {
93
- byteHexMapping[i] = i.toString(16).padStart(2, '0');
94
- }
@@ -17,6 +17,8 @@ const workos_1 = require("../workos");
17
17
  const webhook_json_1 = __importDefault(require("./fixtures/webhook.json"));
18
18
  const workos = new workos_1.WorkOS('sk_test_Sz3IQjepeSWaI4cMS4ms4sMuU');
19
19
  const exceptions_1 = require("../common/exceptions");
20
+ const node_crypto_provider_1 = require("../common/crypto/node-crypto-provider");
21
+ const subtle_crypto_provider_1 = require("../common/crypto/subtle-crypto-provider");
20
22
  describe('Webhooks', () => {
21
23
  let payload;
22
24
  let secret;
@@ -187,4 +189,32 @@ describe('Webhooks', () => {
187
189
  expect(signature).toEqual(signatureHash);
188
190
  }));
189
191
  });
192
+ describe('when in an environment that supports SubtleCrypto', () => {
193
+ it('automatically uses the subtle crypto library', () => {
194
+ // tslint:disable-next-line
195
+ expect(workos.webhooks['cryptoProvider']).toBeInstanceOf(subtle_crypto_provider_1.SubtleCryptoProvider);
196
+ });
197
+ });
198
+ describe('CryptoProvider', () => {
199
+ describe('when computing HMAC signature', () => {
200
+ it('returns the same for the Node crypto and Web Crypto versions', () => __awaiter(void 0, void 0, void 0, function* () {
201
+ const nodeCryptoProvider = new node_crypto_provider_1.NodeCryptoProvider();
202
+ const subtleCryptoProvider = new subtle_crypto_provider_1.SubtleCryptoProvider();
203
+ const stringifiedPayload = JSON.stringify(payload);
204
+ const payloadHMAC = `${timestamp}.${stringifiedPayload}`;
205
+ const nodeCompare = yield nodeCryptoProvider.computeHMACSignatureAsync(payloadHMAC, secret);
206
+ const subtleCompare = yield subtleCryptoProvider.computeHMACSignatureAsync(payloadHMAC, secret);
207
+ expect(nodeCompare).toEqual(subtleCompare);
208
+ }));
209
+ });
210
+ describe('when securely comparing', () => {
211
+ it('returns the same for the Node crypto and Web Crypto versions', () => __awaiter(void 0, void 0, void 0, function* () {
212
+ const nodeCryptoProvider = new node_crypto_provider_1.NodeCryptoProvider();
213
+ const subtleCryptoProvider = new subtle_crypto_provider_1.SubtleCryptoProvider();
214
+ const signature = yield workos.webhooks.computeSignature(timestamp, payload, secret);
215
+ expect(nodeCryptoProvider.secureCompare(signature, signatureHash)).toEqual(subtleCryptoProvider.secureCompare(signature, signatureHash));
216
+ expect(nodeCryptoProvider.secureCompare(signature, 'foo')).toEqual(subtleCryptoProvider.secureCompare(signature, 'foo'));
217
+ }));
218
+ });
219
+ });
190
220
  });
package/lib/workos.d.ts CHANGED
@@ -10,11 +10,12 @@ import { Webhooks } from './webhooks/webhooks';
10
10
  import { Mfa } from './mfa/mfa';
11
11
  import { AuditLogs } from './audit-logs/audit-logs';
12
12
  import { UserManagement } from './user-management/user-management';
13
+ import { HttpClient } from './common/net/http-client';
13
14
  export declare class WorkOS {
14
15
  readonly key?: string | undefined;
15
16
  readonly options: WorkOSOptions;
16
17
  readonly baseURL: string;
17
- private readonly client;
18
+ readonly client: HttpClient;
18
19
  readonly auditLogs: AuditLogs;
19
20
  readonly directorySync: DirectorySync;
20
21
  readonly organizations: Organizations;
@@ -27,6 +28,8 @@ export declare class WorkOS {
27
28
  readonly events: Events;
28
29
  readonly userManagement: UserManagement;
29
30
  constructor(key?: string | undefined, options?: WorkOSOptions);
31
+ createWebhookClient(): Webhooks;
32
+ createHttpClient(options: WorkOSOptions, userAgent: string): HttpClient;
30
33
  get version(): string;
31
34
  post<Result = any, Entity = any>(path: string, entity: Entity, options?: PostOptions): Promise<{
32
35
  data: Result;
@@ -39,5 +42,5 @@ export declare class WorkOS {
39
42
  }>;
40
43
  delete(path: string, query?: any): Promise<void>;
41
44
  emitWarning(warning: string): void;
42
- private handleFetchError;
45
+ private handleHttpError;
43
46
  }
package/lib/workos.js CHANGED
@@ -23,12 +23,13 @@ const mfa_1 = require("./mfa/mfa");
23
23
  const audit_logs_1 = require("./audit-logs/audit-logs");
24
24
  const user_management_1 = require("./user-management/user-management");
25
25
  const bad_request_exception_1 = require("./common/exceptions/bad-request.exception");
26
- const fetch_client_1 = require("./common/utils/fetch-client");
27
- const VERSION = '7.9.0';
26
+ const http_client_1 = require("./common/net/http-client");
27
+ const subtle_crypto_provider_1 = require("./common/crypto/subtle-crypto-provider");
28
+ const fetch_client_1 = require("./common/net/fetch-client");
29
+ const VERSION = '7.11.0';
28
30
  const DEFAULT_HOSTNAME = 'api.workos.com';
29
31
  class WorkOS {
30
32
  constructor(key, options = {}) {
31
- var _a;
32
33
  this.key = key;
33
34
  this.options = options;
34
35
  this.auditLogs = new audit_logs_1.AuditLogs(this);
@@ -38,7 +39,6 @@ class WorkOS {
38
39
  this.passwordless = new passwordless_1.Passwordless(this);
39
40
  this.portal = new portal_1.Portal(this);
40
41
  this.sso = new sso_1.SSO(this);
41
- this.webhooks = new webhooks_1.Webhooks();
42
42
  this.mfa = new mfa_1.Mfa(this);
43
43
  this.events = new events_1.Events(this);
44
44
  this.userManagement = new user_management_1.UserManagement(this);
@@ -64,7 +64,15 @@ class WorkOS {
64
64
  const { name, version } = options.appInfo;
65
65
  userAgent += ` ${name}: ${version}`;
66
66
  }
67
- this.client = new fetch_client_1.FetchClient(this.baseURL, Object.assign(Object.assign({}, options.config), { headers: Object.assign(Object.assign({}, (_a = options.config) === null || _a === void 0 ? void 0 : _a.headers), { Authorization: `Bearer ${this.key}`, 'User-Agent': userAgent }) }));
67
+ this.webhooks = this.createWebhookClient();
68
+ this.client = this.createHttpClient(options, userAgent);
69
+ }
70
+ createWebhookClient() {
71
+ return new webhooks_1.Webhooks(new subtle_crypto_provider_1.SubtleCryptoProvider());
72
+ }
73
+ createHttpClient(options, userAgent) {
74
+ var _a;
75
+ return new fetch_client_1.FetchHttpClient(this.baseURL, Object.assign(Object.assign({}, options.config), { headers: Object.assign(Object.assign({}, (_a = options.config) === null || _a === void 0 ? void 0 : _a.headers), { Authorization: `Bearer ${this.key}`, 'User-Agent': userAgent }) }));
68
76
  }
69
77
  get version() {
70
78
  return VERSION;
@@ -76,13 +84,14 @@ class WorkOS {
76
84
  requestHeaders['Idempotency-Key'] = options.idempotencyKey;
77
85
  }
78
86
  try {
79
- return yield this.client.post(path, entity, {
87
+ const res = yield this.client.post(path, entity, {
80
88
  params: options.query,
81
89
  headers: requestHeaders,
82
90
  });
91
+ return { data: yield res.toJSON() };
83
92
  }
84
93
  catch (error) {
85
- this.handleFetchError({ path, error });
94
+ this.handleHttpError({ path, error });
86
95
  throw error;
87
96
  }
88
97
  });
@@ -91,15 +100,16 @@ class WorkOS {
91
100
  return __awaiter(this, void 0, void 0, function* () {
92
101
  try {
93
102
  const { accessToken } = options;
94
- return yield this.client.get(path, {
103
+ const res = yield this.client.get(path, {
95
104
  params: options.query,
96
105
  headers: accessToken
97
106
  ? { Authorization: `Bearer ${accessToken}` }
98
107
  : undefined,
99
108
  });
109
+ return { data: yield res.toJSON() };
100
110
  }
101
111
  catch (error) {
102
- this.handleFetchError({ path, error });
112
+ this.handleHttpError({ path, error });
103
113
  throw error;
104
114
  }
105
115
  });
@@ -111,13 +121,14 @@ class WorkOS {
111
121
  requestHeaders['Idempotency-Key'] = options.idempotencyKey;
112
122
  }
113
123
  try {
114
- return yield this.client.put(path, entity, {
124
+ const res = yield this.client.put(path, entity, {
115
125
  params: options.query,
116
126
  headers: requestHeaders,
117
127
  });
128
+ return { data: yield res.toJSON() };
118
129
  }
119
130
  catch (error) {
120
- this.handleFetchError({ path, error });
131
+ this.handleHttpError({ path, error });
121
132
  throw error;
122
133
  }
123
134
  });
@@ -130,7 +141,7 @@ class WorkOS {
130
141
  });
131
142
  }
132
143
  catch (error) {
133
- this.handleFetchError({ path, error });
144
+ this.handleHttpError({ path, error });
134
145
  throw error;
135
146
  }
136
147
  });
@@ -143,12 +154,15 @@ class WorkOS {
143
154
  }
144
155
  return process.emitWarning(warning, 'WorkOS');
145
156
  }
146
- handleFetchError({ path, error }) {
157
+ handleHttpError({ path, error }) {
147
158
  var _a;
159
+ if (!(error instanceof http_client_1.HttpClientError)) {
160
+ throw new Error(`Unexpected error: ${error}`);
161
+ }
148
162
  const { response } = error;
149
163
  if (response) {
150
164
  const { status, data, headers } = response;
151
- const requestID = (_a = headers.get('X-Request-ID')) !== null && _a !== void 0 ? _a : '';
165
+ const requestID = (_a = headers['X-Request-ID']) !== null && _a !== void 0 ? _a : '';
152
166
  const { code, error_description: errorDescription, error, errors, message, } = data;
153
167
  switch (status) {
154
168
  case 401: {