@salesforce/core 4.0.0-v3.0 → 4.0.1

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 (160) hide show
  1. package/LICENSE.txt +1 -1
  2. package/README.md +93 -44
  3. package/lib/config/aliasesConfig.d.ts +12 -0
  4. package/lib/config/aliasesConfig.js +28 -0
  5. package/lib/config/authInfoConfig.d.ts +19 -0
  6. package/lib/config/authInfoConfig.js +35 -0
  7. package/lib/config/config.d.ts +181 -48
  8. package/lib/config/config.js +382 -159
  9. package/lib/config/configAggregator.d.ts +59 -42
  10. package/lib/config/configAggregator.js +135 -82
  11. package/lib/config/configFile.d.ts +2 -2
  12. package/lib/config/configFile.js +40 -31
  13. package/lib/config/configGroup.d.ts +9 -9
  14. package/lib/config/configGroup.js +13 -11
  15. package/lib/config/configStore.d.ts +9 -9
  16. package/lib/config/configStore.js +29 -26
  17. package/lib/config/envVars.d.ts +102 -0
  18. package/lib/config/envVars.js +457 -0
  19. package/lib/config/orgUsersConfig.d.ts +8 -0
  20. package/lib/config/orgUsersConfig.js +12 -0
  21. package/lib/config/sandboxOrgConfig.d.ts +8 -0
  22. package/lib/config/sandboxOrgConfig.js +12 -0
  23. package/lib/config/sandboxProcessCache.d.ts +16 -0
  24. package/lib/config/sandboxProcessCache.js +38 -0
  25. package/lib/config/tokensConfig.d.ts +10 -0
  26. package/lib/config/tokensConfig.js +29 -0
  27. package/lib/config/ttlConfig.d.ts +34 -0
  28. package/lib/config/ttlConfig.js +50 -0
  29. package/lib/crypto/crypto.js +29 -16
  30. package/lib/crypto/keyChain.js +4 -4
  31. package/lib/crypto/keyChainImpl.d.ts +5 -3
  32. package/lib/crypto/keyChainImpl.js +65 -66
  33. package/lib/crypto/secureBuffer.d.ts +1 -1
  34. package/lib/crypto/secureBuffer.js +1 -1
  35. package/lib/deviceOauthService.d.ts +5 -5
  36. package/lib/deviceOauthService.js +37 -33
  37. package/lib/exported.d.ts +22 -15
  38. package/lib/exported.js +49 -25
  39. package/lib/global.d.ts +17 -3
  40. package/lib/global.js +46 -13
  41. package/lib/lifecycleEvents.d.ts +39 -2
  42. package/lib/lifecycleEvents.js +77 -3
  43. package/lib/logger.d.ts +21 -11
  44. package/lib/logger.js +121 -105
  45. package/lib/messages.d.ts +53 -36
  46. package/lib/messages.js +89 -97
  47. package/lib/org/authInfo.d.ts +84 -72
  48. package/lib/org/authInfo.js +326 -320
  49. package/lib/org/authRemover.d.ts +16 -23
  50. package/lib/org/authRemover.js +62 -60
  51. package/lib/org/connection.d.ts +33 -59
  52. package/lib/org/connection.js +129 -190
  53. package/lib/org/index.js +6 -2
  54. package/lib/org/org.d.ts +263 -38
  55. package/lib/org/org.js +734 -149
  56. package/lib/org/orgConfigProperties.d.ts +69 -0
  57. package/lib/org/orgConfigProperties.js +121 -0
  58. package/lib/org/permissionSetAssignment.js +6 -15
  59. package/lib/org/scratchOrgCache.d.ts +20 -0
  60. package/lib/org/scratchOrgCache.js +33 -0
  61. package/lib/org/scratchOrgCreate.d.ts +54 -0
  62. package/lib/org/scratchOrgCreate.js +214 -0
  63. package/lib/org/scratchOrgErrorCodes.d.ts +10 -0
  64. package/lib/org/scratchOrgErrorCodes.js +79 -0
  65. package/lib/org/scratchOrgFeatureDeprecation.d.ts +26 -0
  66. package/lib/org/scratchOrgFeatureDeprecation.js +105 -0
  67. package/lib/org/scratchOrgInfoApi.d.ts +68 -0
  68. package/lib/org/scratchOrgInfoApi.js +416 -0
  69. package/lib/org/scratchOrgInfoGenerator.d.ts +64 -0
  70. package/lib/org/scratchOrgInfoGenerator.js +237 -0
  71. package/lib/org/scratchOrgLifecycleEvents.d.ts +10 -0
  72. package/lib/org/scratchOrgLifecycleEvents.js +41 -0
  73. package/lib/org/scratchOrgSettingsGenerator.d.ts +79 -0
  74. package/lib/org/scratchOrgSettingsGenerator.js +277 -0
  75. package/lib/org/scratchOrgTypes.d.ts +43 -0
  76. package/lib/{status/client.js → org/scratchOrgTypes.js} +1 -1
  77. package/lib/org/user.d.ts +7 -2
  78. package/lib/org/user.js +78 -54
  79. package/lib/schema/printer.d.ts +6 -0
  80. package/lib/schema/printer.js +49 -46
  81. package/lib/schema/validator.d.ts +12 -10
  82. package/lib/schema/validator.js +56 -76
  83. package/lib/{sfdxError.d.ts → sfError.d.ts} +12 -15
  84. package/lib/{sfdxError.js → sfError.js} +42 -24
  85. package/lib/{sfdxProject.d.ts → sfProject.d.ts} +75 -35
  86. package/lib/sfProject.js +651 -0
  87. package/lib/stateAggregator/accessors/aliasAccessor.d.ts +98 -0
  88. package/lib/stateAggregator/accessors/aliasAccessor.js +146 -0
  89. package/lib/stateAggregator/accessors/orgAccessor.d.ts +101 -0
  90. package/lib/stateAggregator/accessors/orgAccessor.js +240 -0
  91. package/lib/stateAggregator/accessors/sandboxAccessor.d.ts +8 -0
  92. package/lib/stateAggregator/accessors/sandboxAccessor.js +28 -0
  93. package/lib/stateAggregator/accessors/tokenAccessor.d.ts +63 -0
  94. package/lib/stateAggregator/accessors/tokenAccessor.js +80 -0
  95. package/lib/stateAggregator/index.d.ts +4 -0
  96. package/lib/stateAggregator/index.js +27 -0
  97. package/lib/stateAggregator/stateAggregator.d.ts +25 -0
  98. package/lib/stateAggregator/stateAggregator.js +46 -0
  99. package/lib/status/myDomainResolver.d.ts +1 -1
  100. package/lib/status/myDomainResolver.js +10 -10
  101. package/lib/status/pollingClient.d.ts +2 -6
  102. package/lib/status/pollingClient.js +38 -64
  103. package/lib/status/streamingClient.d.ts +5 -80
  104. package/lib/status/streamingClient.js +74 -94
  105. package/lib/status/types.d.ts +89 -0
  106. package/lib/status/types.js +18 -0
  107. package/lib/testSetup.d.ts +212 -79
  108. package/lib/testSetup.js +478 -182
  109. package/lib/util/cache.d.ts +11 -0
  110. package/lib/util/cache.js +70 -0
  111. package/lib/util/checkLightningDomain.d.ts +1 -0
  112. package/lib/util/checkLightningDomain.js +29 -0
  113. package/lib/util/directoryWriter.d.ts +12 -0
  114. package/lib/util/directoryWriter.js +54 -0
  115. package/lib/util/getJwtAudienceUrl.d.ts +4 -0
  116. package/lib/util/getJwtAudienceUrl.js +19 -0
  117. package/lib/util/internal.d.ts +28 -2
  118. package/lib/util/internal.js +65 -8
  119. package/lib/util/jsonXmlTools.d.ts +14 -0
  120. package/lib/util/jsonXmlTools.js +39 -0
  121. package/lib/util/mapKeys.d.ts +14 -0
  122. package/lib/util/mapKeys.js +52 -0
  123. package/lib/util/sfdc.d.ts +51 -63
  124. package/lib/util/sfdc.js +75 -127
  125. package/lib/util/sfdcUrl.d.ts +64 -0
  126. package/lib/util/sfdcUrl.js +197 -0
  127. package/lib/util/structuredWriter.d.ts +9 -0
  128. package/lib/util/structuredWriter.js +3 -0
  129. package/lib/util/zipWriter.d.ts +16 -0
  130. package/lib/util/zipWriter.js +68 -0
  131. package/lib/webOAuthServer.d.ts +20 -7
  132. package/lib/webOAuthServer.js +107 -60
  133. package/messageTransformer/messageTransformer.ts +93 -0
  134. package/messages/auth.md +11 -3
  135. package/messages/config.md +94 -6
  136. package/messages/connection.md +8 -0
  137. package/messages/core.json +3 -3
  138. package/messages/core.md +11 -1
  139. package/messages/envVars.md +313 -0
  140. package/messages/org.md +64 -0
  141. package/messages/scratchOrgCreate.md +23 -0
  142. package/messages/scratchOrgErrorCodes.md +115 -0
  143. package/messages/scratchOrgFeatureDeprecation.md +11 -0
  144. package/messages/scratchOrgInfoApi.md +20 -0
  145. package/messages/scratchOrgInfoGenerator.md +27 -0
  146. package/messages/user.md +12 -0
  147. package/package.json +138 -66
  148. package/CHANGELOG.md +0 -699
  149. package/lib/config/aliases.d.ts +0 -56
  150. package/lib/config/aliases.js +0 -96
  151. package/lib/config/globalInfoConfig.d.ts +0 -74
  152. package/lib/config/globalInfoConfig.js +0 -144
  153. package/lib/config/keychainConfig.d.ts +0 -19
  154. package/lib/config/keychainConfig.js +0 -43
  155. package/lib/config/sfdxDataHandler.d.ts +0 -36
  156. package/lib/config/sfdxDataHandler.js +0 -165
  157. package/lib/sfdxProject.js +0 -546
  158. package/lib/status/client.d.ts +0 -15
  159. package/lib/util/fs.d.ts +0 -198
  160. package/lib/util/fs.js +0 -374
package/lib/util/sfdc.js CHANGED
@@ -6,137 +6,85 @@
6
6
  * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.sfdc = void 0;
10
- const url_1 = require("url");
9
+ exports.matchesAccessToken = exports.findUpperCaseKeys = exports.validatePathDoesNotContainInvalidChars = exports.validateSalesforceId = exports.isInternalUrl = exports.validateEmail = exports.validateApiVersion = exports.trimTo15 = void 0;
11
10
  const kit_1 = require("@salesforce/kit");
12
11
  const ts_types_1 = require("@salesforce/ts-types");
13
- exports.sfdc = {
14
- /**
15
- * Returns `true` if a provided URL contains a Salesforce owned domain.
16
- *
17
- * @param urlString The URL to inspect.
18
- */
19
- isSalesforceDomain: (urlString) => {
20
- let url;
21
- try {
22
- url = new url_1.URL(urlString);
23
- }
24
- catch (e) {
25
- return false;
26
- }
27
- // Source https://help.salesforce.com/articleView?id=000003652&type=1
28
- const allowlistOfSalesforceDomainPatterns = [
29
- '.cloudforce.com',
30
- '.content.force.com',
31
- '.force.com',
32
- '.salesforce.com',
33
- '.salesforceliveagent.com',
34
- '.secure.force.com',
35
- ];
36
- const allowlistOfSalesforceHosts = ['developer.salesforce.com', 'trailhead.salesforce.com'];
37
- return allowlistOfSalesforceDomainPatterns.some((pattern) => {
38
- return url.hostname.endsWith(pattern) || allowlistOfSalesforceHosts.includes(url.hostname);
39
- });
40
- },
41
- /**
42
- * Converts an 18 character Salesforce ID to 15 characters.
43
- *
44
- * @param id The id to convert.
45
- */
46
- trimTo15: (id) => {
47
- if (id && id.length && id.length > 15) {
48
- id = id.substring(0, 15);
12
+ const sfdcUrl_1 = require("./sfdcUrl");
13
+ function trimTo15(id) {
14
+ if (!id) {
15
+ return undefined;
16
+ }
17
+ if (id.length && id.length > 15) {
18
+ id = id.substring(0, 15);
19
+ }
20
+ return id;
21
+ }
22
+ exports.trimTo15 = trimTo15;
23
+ /**
24
+ * Tests whether an API version matches the format `i.0`.
25
+ *
26
+ * @param value The API version as a string.
27
+ */
28
+ const validateApiVersion = (value) => value == null || /^[1-9]\d\.0$/.test(value);
29
+ exports.validateApiVersion = validateApiVersion;
30
+ /**
31
+ * Tests whether an email matches the format `me@my.org`
32
+ *
33
+ * @param value The email as a string.
34
+ */
35
+ const validateEmail = (value) => /^[^.][^@]*@[^.]+(\.[^.\s]+)+$/.test(value);
36
+ exports.validateEmail = validateEmail;
37
+ /**
38
+ * Tests whether a given url is an internal Salesforce domain
39
+ *
40
+ * @param url
41
+ */
42
+ const isInternalUrl = (url) => new sfdcUrl_1.SfdcUrl(url).isInternalUrl();
43
+ exports.isInternalUrl = isInternalUrl;
44
+ /**
45
+ * Tests whether a Salesforce ID is in the correct format, a 15- or 18-character length string with only letters and numbers
46
+ *
47
+ * @param value The ID as a string.
48
+ */
49
+ const validateSalesforceId = (value) => /[a-zA-Z0-9]{18}|[a-zA-Z0-9]{15}/.test(value) && (value.length === 15 || value.length === 18);
50
+ exports.validateSalesforceId = validateSalesforceId;
51
+ /**
52
+ * Tests whether a path is in the correct format; the value doesn't include the characters "[", "]", "?", "<", ">", "?", "|"
53
+ *
54
+ * @param value The path as a string.
55
+ */
56
+ const validatePathDoesNotContainInvalidChars = (value) =>
57
+ // eslint-disable-next-line no-useless-escape
58
+ !/[\["\?<>\|\]]+/.test(value);
59
+ exports.validatePathDoesNotContainInvalidChars = validatePathDoesNotContainInvalidChars;
60
+ /**
61
+ * Returns the first key within the object that has an upper case first letter.
62
+ *
63
+ * @param data The object in which to check key casing.
64
+ * @param sectionBlocklist properties in the object to exclude from the search. e.g. a blocklist of `["a"]` and data of `{ "a": { "B" : "b"}}` would ignore `B` because it is in the object value under `a`.
65
+ */
66
+ const findUpperCaseKeys = (data, sectionBlocklist = []) => {
67
+ let key;
68
+ (0, kit_1.findKey)(data, (val, k) => {
69
+ if (/^[A-Z]/.test(k)) {
70
+ key = k;
49
71
  }
50
- return id;
51
- },
52
- /**
53
- * Tests whether an API version matches the format `i.0`.
54
- *
55
- * @param value The API version as a string.
56
- */
57
- validateApiVersion: (value) => {
58
- return value == null || /^[1-9]\d\.0$/.test(value);
59
- },
60
- /**
61
- * Tests whether an email matches the format `me@my.org`
62
- *
63
- * @param value The email as a string.
64
- */
65
- validateEmail: (value) => {
66
- return /^[^.][^@]*@[^.]+(\.[^.\s]+)+$/.test(value);
67
- },
68
- /**
69
- * Tests whether a Salesforce ID is in the correct format, a 15- or 18-character length string with only letters and numbers
70
- *
71
- * @param value The ID as a string.
72
- */
73
- validateSalesforceId: (value) => {
74
- return /[a-zA-Z0-9]{18}|[a-zA-Z0-9]{15}/.test(value) && (value.length === 15 || value.length === 18);
75
- },
76
- /**
77
- * Tests whether a path is in the correct format; the value doesn't include the characters "[", "]", "?", "<", ">", "?", "|"
78
- *
79
- * @param value The path as a string.
80
- */
81
- validatePathDoesNotContainInvalidChars: (value) => {
82
- // eslint-disable-next-line no-useless-escape
83
- return !/[\["\?<>\|\]]+/.test(value);
84
- },
85
- /**
86
- * Returns the first key within the object that has an upper case first letter.
87
- *
88
- * @param data The object in which to check key casing.
89
- * @param sectionBlocklist properties in the object to exclude from the search. e.g. a blocklist of `["a"]` and data of `{ "a": { "B" : "b"}}` would ignore `B` because it is in the object value under `a`.
90
- */
91
- findUpperCaseKeys: (data, sectionBlocklist = []) => {
92
- let key;
93
- kit_1.findKey(data, (val, k) => {
94
- if (k.substr(0, 1) === k.substr(0, 1).toUpperCase()) {
95
- key = k;
96
- }
97
- else if (ts_types_1.isJsonMap(val)) {
98
- if (sectionBlocklist.includes(k)) {
99
- return key;
100
- }
101
- key = exports.sfdc.findUpperCaseKeys(ts_types_1.asJsonMap(val));
72
+ else if ((0, ts_types_1.isJsonMap)(val)) {
73
+ if (sectionBlocklist.includes(k)) {
74
+ return key;
102
75
  }
103
- return key;
104
- });
76
+ key = (0, exports.findUpperCaseKeys)((0, ts_types_1.asJsonMap)(val));
77
+ }
105
78
  return key;
106
- },
107
- /**
108
- * Tests whether a given string is an access token
109
- *
110
- * @param value
111
- */
112
- matchesAccessToken: (value) => {
113
- return /^(00D\w{12,15})![.\w]*$/.test(value);
114
- },
115
- /**
116
- * Tests whether a given url is an internal Salesforce domain
117
- *
118
- * @param url
119
- */
120
- isInternalUrl: (url) => {
121
- const INTERNAL_URL_PARTS = [
122
- '.vpod.',
123
- 'stm.salesforce.com',
124
- 'stm.force.com',
125
- '.blitz.salesforce.com',
126
- '.stm.salesforce.ms',
127
- '.pc-rnd.force.com',
128
- '.pc-rnd.salesforce.com',
129
- ];
130
- return (url.startsWith('https://gs1.') || exports.sfdc.isLocalUrl(url) || INTERNAL_URL_PARTS.some((part) => url.includes(part)));
131
- },
132
- /**
133
- * Tests whether a given internal url runs on a local machine
134
- *
135
- * @param url
136
- */
137
- isLocalUrl: (url) => {
138
- const LOCAL_PARTS = ['localhost.sfdcdev.', '.internal.'];
139
- return LOCAL_PARTS.some((part) => url.includes(part));
140
- },
79
+ });
80
+ return key;
141
81
  };
82
+ exports.findUpperCaseKeys = findUpperCaseKeys;
83
+ /**
84
+ * Tests whether a given string is an access token
85
+ *
86
+ * @param value
87
+ */
88
+ const matchesAccessToken = (value) => /^(00D\w{12,15})![.\w]*$/.test(value);
89
+ exports.matchesAccessToken = matchesAccessToken;
142
90
  //# sourceMappingURL=sfdc.js.map
@@ -0,0 +1,64 @@
1
+ /// <reference types="node" />
2
+ import { URL } from 'url';
3
+ export declare function getLoginAudienceCombos(audienceUrl: string, loginUrl: string): Array<[string, string]>;
4
+ export declare class SfdcUrl extends URL {
5
+ /**
6
+ * Salesforce URLs
7
+ */
8
+ static readonly SANDBOX = "https://test.salesforce.com";
9
+ static readonly PRODUCTION = "https://login.salesforce.com";
10
+ private static readonly cache;
11
+ private logger;
12
+ constructor(input: string | URL, base?: string | URL);
13
+ static isValidUrl(input: string | URL): boolean;
14
+ /**
15
+ * Returns the appropriate jwt audience url for this url
16
+ * Use SFDX_AUDIENCE_URL env var to override the audience url
17
+ *
18
+ * @param createdOrgInstance The Salesforce instance the org was created on. e.g. `cs42`
19
+ * @return {Promise<string>} The audience url
20
+ */
21
+ getJwtAudienceUrl(createdOrgInstance?: string): Promise<string>;
22
+ /**
23
+ * Tests whether this url contains a Salesforce owned domain
24
+ *
25
+ * @return {boolean} true if this is a salesforce domain
26
+ */
27
+ isSalesforceDomain(): boolean;
28
+ /**
29
+ * Tests whether this url is an internal Salesforce domain
30
+ *
31
+ * @returns {boolean} true if this is an internal domain
32
+ */
33
+ isInternalUrl(): boolean;
34
+ /**
35
+ * Tests whether this url runs on a local machine
36
+ *
37
+ * @returns {boolean} true if this is a local machine
38
+ */
39
+ isLocalUrl(): boolean;
40
+ toLightningDomain(): string;
41
+ /**
42
+ * Tests whether this url has the lightning domain extension
43
+ * This method that performs the dns lookup of the host. If the lookup fails the internal polling (1 second), client will try again until timeout
44
+ * If SFDX_DOMAIN_RETRY environment variable is set (number) it overrides the default timeout duration (240 seconds)
45
+ *
46
+ * @returns {Promise<true | never>} The resolved ip address or never
47
+ * @throws {@link SfError} If can't resolve DNS.
48
+ */
49
+ checkLightningDomain(): Promise<true | never>;
50
+ /**
51
+ * Method that performs the dns lookup of the host. If the lookup fails the internal polling (1 second), client will try again until timeout
52
+ * If SFDX_DOMAIN_RETRY environment variable is set (number) it overrides the default timeout duration (240 seconds)
53
+ *
54
+ * @returns the resolved ip address.
55
+ * @throws {@link SfError} If can't resolve DNS.
56
+ */
57
+ lookup(): Promise<string>;
58
+ /**
59
+ * Test whether this url represents a lightning domain
60
+ *
61
+ * @returns {boolean} true if this domain is a lightning domain
62
+ */
63
+ isLightningDomain(): boolean;
64
+ }
@@ -0,0 +1,197 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright (c) 2021, salesforce.com, inc.
4
+ * All rights reserved.
5
+ * Licensed under the BSD 3-Clause license.
6
+ * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.SfdcUrl = exports.getLoginAudienceCombos = void 0;
10
+ const url_1 = require("url");
11
+ const kit_1 = require("@salesforce/kit");
12
+ const ts_types_1 = require("@salesforce/ts-types");
13
+ const myDomainResolver_1 = require("../status/myDomainResolver");
14
+ const logger_1 = require("../logger");
15
+ const lifecycleEvents_1 = require("../lifecycleEvents");
16
+ function getLoginAudienceCombos(audienceUrl, loginUrl) {
17
+ const filtered = [
18
+ [loginUrl, loginUrl],
19
+ [SfdcUrl.SANDBOX, SfdcUrl.SANDBOX],
20
+ [SfdcUrl.PRODUCTION, SfdcUrl.PRODUCTION],
21
+ [audienceUrl, audienceUrl],
22
+ [audienceUrl, SfdcUrl.PRODUCTION],
23
+ [audienceUrl, SfdcUrl.SANDBOX],
24
+ [loginUrl, audienceUrl],
25
+ [loginUrl, SfdcUrl.PRODUCTION],
26
+ [loginUrl, SfdcUrl.SANDBOX],
27
+ [SfdcUrl.PRODUCTION, audienceUrl],
28
+ [SfdcUrl.SANDBOX, audienceUrl],
29
+ ].filter(([login, audience]) => !((login === SfdcUrl.PRODUCTION && audience === SfdcUrl.SANDBOX) ||
30
+ (login === SfdcUrl.SANDBOX && audience === SfdcUrl.PRODUCTION)));
31
+ const reduced = filtered.reduce((acc, [login, audience]) => {
32
+ const l = new url_1.URL(login);
33
+ const a = new url_1.URL(audience);
34
+ acc.set(`${l.origin}:${a.origin}`, [login, audience]);
35
+ return acc;
36
+ }, new Map());
37
+ return [...reduced.values()];
38
+ }
39
+ exports.getLoginAudienceCombos = getLoginAudienceCombos;
40
+ class SfdcUrl extends url_1.URL {
41
+ constructor(input, base) {
42
+ super(input.toString(), base);
43
+ if (this.protocol !== 'https:' && !SfdcUrl.cache.has(this.origin)) {
44
+ SfdcUrl.cache.add(this.origin);
45
+ void lifecycleEvents_1.Lifecycle.getInstance().emitWarning(`Using insecure protocol: ${this.protocol} on url: ${this.origin}`);
46
+ }
47
+ }
48
+ static isValidUrl(input) {
49
+ try {
50
+ new url_1.URL(input.toString());
51
+ return true;
52
+ }
53
+ catch {
54
+ return false;
55
+ }
56
+ }
57
+ /**
58
+ * Returns the appropriate jwt audience url for this url
59
+ * Use SFDX_AUDIENCE_URL env var to override the audience url
60
+ *
61
+ * @param createdOrgInstance The Salesforce instance the org was created on. e.g. `cs42`
62
+ * @return {Promise<string>} The audience url
63
+ */
64
+ async getJwtAudienceUrl(createdOrgInstance) {
65
+ this.logger = await logger_1.Logger.child('SfdcUrl');
66
+ // environment variable is used as an override
67
+ const envVarVal = new kit_1.Env().getString('SFDX_AUDIENCE_URL', '');
68
+ if (envVarVal) {
69
+ this.logger.debug(`Audience URL overridden by env var SFDX_AUDIENCE_URL=${envVarVal}`);
70
+ return envVarVal;
71
+ }
72
+ if ((createdOrgInstance && /^gs1/gi.test(createdOrgInstance)) || /(gs1.my.salesforce.com)/gi.test(this.origin)) {
73
+ return 'https://gs1.salesforce.com';
74
+ }
75
+ return SfdcUrl.PRODUCTION;
76
+ }
77
+ /**
78
+ * Tests whether this url contains a Salesforce owned domain
79
+ *
80
+ * @return {boolean} true if this is a salesforce domain
81
+ */
82
+ isSalesforceDomain() {
83
+ // Source https://help.salesforce.com/articleView?id=000003652&type=1
84
+ const allowlistOfSalesforceDomainPatterns = [
85
+ '.cloudforce.com',
86
+ '.content.force.com',
87
+ '.force.com',
88
+ '.salesforce.com',
89
+ '.salesforceliveagent.com',
90
+ '.secure.force.com',
91
+ 'crmforce.mil',
92
+ ];
93
+ const allowlistOfSalesforceHosts = ['developer.salesforce.com', 'trailhead.salesforce.com'];
94
+ return allowlistOfSalesforceDomainPatterns.some((pattern) => this.hostname.endsWith(pattern) || allowlistOfSalesforceHosts.includes(this.hostname));
95
+ }
96
+ /**
97
+ * Tests whether this url is an internal Salesforce domain
98
+ *
99
+ * @returns {boolean} true if this is an internal domain
100
+ */
101
+ isInternalUrl() {
102
+ const INTERNAL_URL_PARTS = [
103
+ '.vpod.',
104
+ 'stm.salesforce.com',
105
+ 'stm.force.com',
106
+ '.blitz.salesforce.com',
107
+ '.stm.salesforce.ms',
108
+ '.pc-rnd.force.com',
109
+ '.pc-rnd.salesforce.com',
110
+ ];
111
+ return (this.origin.startsWith('https://gs1.') ||
112
+ this.isLocalUrl() ||
113
+ INTERNAL_URL_PARTS.some((part) => this.origin.includes(part)));
114
+ }
115
+ /**
116
+ * Tests whether this url runs on a local machine
117
+ *
118
+ * @returns {boolean} true if this is a local machine
119
+ */
120
+ isLocalUrl() {
121
+ const LOCAL_PARTS = ['localhost.sfdcdev.', '.internal.'];
122
+ return LOCAL_PARTS.some((part) => this.origin.includes(part));
123
+ }
124
+ toLightningDomain() {
125
+ if (this.origin.endsWith('.my.salesforce.mil')) {
126
+ return this.origin.replace('.my.salesforce.mil', '.lightning.crmforce.mil');
127
+ }
128
+ // enhanced domains
129
+ // ex: sandbox.my.salesforce.com, scratch.my.salesforce.com, etc
130
+ if (this.origin.endsWith('.my.salesforce.com')) {
131
+ return this.origin.replace('.my.salesforce.com', '.lightning.force.com');
132
+ }
133
+ // alternative domains
134
+ if (this.origin.endsWith('.my-salesforce.com')) {
135
+ return this.origin.replace('.my-salesforce.com', '.my-lightning.com');
136
+ }
137
+ // all non-mil domains
138
+ return `https://${(0, ts_types_1.ensureArray)(/https?:\/\/([^.]*)/.exec(this.origin))
139
+ .slice(1, 2)
140
+ .pop()}.lightning.force.com`;
141
+ }
142
+ /**
143
+ * Tests whether this url has the lightning domain extension
144
+ * This method that performs the dns lookup of the host. If the lookup fails the internal polling (1 second), client will try again until timeout
145
+ * If SFDX_DOMAIN_RETRY environment variable is set (number) it overrides the default timeout duration (240 seconds)
146
+ *
147
+ * @returns {Promise<true | never>} The resolved ip address or never
148
+ * @throws {@link SfError} If can't resolve DNS.
149
+ */
150
+ async checkLightningDomain() {
151
+ const quantity = (0, ts_types_1.ensureNumber)(new kit_1.Env().getNumber('SFDX_DOMAIN_RETRY', 240));
152
+ const timeout = new kit_1.Duration(quantity, kit_1.Duration.Unit.SECONDS);
153
+ if (this.isInternalUrl() || timeout.seconds === 0) {
154
+ return true;
155
+ }
156
+ const resolver = await myDomainResolver_1.MyDomainResolver.create({
157
+ url: new url_1.URL(this.toLightningDomain()),
158
+ timeout,
159
+ frequency: new kit_1.Duration(1, kit_1.Duration.Unit.SECONDS),
160
+ });
161
+ await resolver.resolve();
162
+ return true;
163
+ }
164
+ /**
165
+ * Method that performs the dns lookup of the host. If the lookup fails the internal polling (1 second), client will try again until timeout
166
+ * If SFDX_DOMAIN_RETRY environment variable is set (number) it overrides the default timeout duration (240 seconds)
167
+ *
168
+ * @returns the resolved ip address.
169
+ * @throws {@link SfError} If can't resolve DNS.
170
+ */
171
+ async lookup() {
172
+ const quantity = (0, ts_types_1.ensureNumber)(new kit_1.Env().getNumber('SFDX_DOMAIN_RETRY', 240));
173
+ const timeout = new kit_1.Duration(quantity, kit_1.Duration.Unit.SECONDS);
174
+ const resolver = await myDomainResolver_1.MyDomainResolver.create({
175
+ url: new url_1.URL(this.origin),
176
+ timeout,
177
+ frequency: new kit_1.Duration(1, kit_1.Duration.Unit.SECONDS),
178
+ });
179
+ return resolver.resolve();
180
+ }
181
+ /**
182
+ * Test whether this url represents a lightning domain
183
+ *
184
+ * @returns {boolean} true if this domain is a lightning domain
185
+ */
186
+ isLightningDomain() {
187
+ return this.origin.includes('.lightning.force.com') || this.origin.includes('.lightning.crmforce.mil');
188
+ }
189
+ }
190
+ exports.SfdcUrl = SfdcUrl;
191
+ /**
192
+ * Salesforce URLs
193
+ */
194
+ SfdcUrl.SANDBOX = 'https://test.salesforce.com';
195
+ SfdcUrl.PRODUCTION = 'https://login.salesforce.com';
196
+ SfdcUrl.cache = new Set();
197
+ //# sourceMappingURL=sfdcUrl.js.map
@@ -0,0 +1,9 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
3
+ import { Readable } from 'stream';
4
+ export interface StructuredWriter {
5
+ addToStore(contents: string | Readable | Buffer, path: string): Promise<void>;
6
+ finalize(): Promise<void>;
7
+ getDestinationPath(): string | undefined;
8
+ get buffer(): Buffer;
9
+ }
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=structuredWriter.js.map
@@ -0,0 +1,16 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
3
+ import { Readable, Writable } from 'stream';
4
+ import { StructuredWriter } from './structuredWriter';
5
+ export declare class ZipWriter extends Writable implements StructuredWriter {
6
+ private readonly rootDestination?;
7
+ private zip;
8
+ private buffers;
9
+ constructor(rootDestination?: string | undefined);
10
+ get buffer(): Buffer;
11
+ addToStore(contents: string | Readable | Buffer, path: string): Promise<void>;
12
+ finalize(): Promise<void>;
13
+ getDestinationPath(): string | undefined;
14
+ private getOutputStream;
15
+ private getInputBuffer;
16
+ }
@@ -0,0 +1,68 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright (c) 2021, salesforce.com, inc.
4
+ * All rights reserved.
5
+ * Licensed under the BSD 3-Clause license.
6
+ * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.ZipWriter = void 0;
10
+ const fs_1 = require("fs");
11
+ const stream_1 = require("stream");
12
+ const util_1 = require("util");
13
+ const archiver_1 = require("archiver");
14
+ const pipeline = (0, util_1.promisify)(stream_1.pipeline);
15
+ class ZipWriter extends stream_1.Writable {
16
+ constructor(rootDestination) {
17
+ super({ objectMode: true });
18
+ this.rootDestination = rootDestination;
19
+ // compression-/speed+ (0)<---(3)---------->(9) compression+/speed-
20
+ // 3 appears to be a decent balance of compression and speed. It felt like
21
+ // higher values = diminishing returns on compression and made conversion slower
22
+ this.zip = (0, archiver_1.create)('zip', { zlib: { level: 3 } });
23
+ this.buffers = [];
24
+ void pipeline(this.zip, this.getOutputStream());
25
+ }
26
+ get buffer() {
27
+ return Buffer.concat(this.buffers);
28
+ }
29
+ async addToStore(contents, path) {
30
+ this.zip.append(contents, { name: path });
31
+ return Promise.resolve();
32
+ }
33
+ async finalize() {
34
+ await this.zip.finalize();
35
+ await this.getInputBuffer();
36
+ }
37
+ getDestinationPath() {
38
+ return this.rootDestination;
39
+ }
40
+ getOutputStream() {
41
+ if (this.rootDestination) {
42
+ return (0, fs_1.createWriteStream)(this.rootDestination);
43
+ }
44
+ else {
45
+ const bufferWritable = new stream_1.Writable();
46
+ // eslint-disable-next-line no-underscore-dangle
47
+ bufferWritable._write = (chunk, encoding, cb) => {
48
+ this.buffers.push(chunk);
49
+ cb();
50
+ };
51
+ return bufferWritable;
52
+ }
53
+ }
54
+ async getInputBuffer() {
55
+ if (this.rootDestination) {
56
+ const inputStream = (0, fs_1.createReadStream)(this.rootDestination);
57
+ return new Promise((resolve, reject) => {
58
+ inputStream.on('data', (chunk) => {
59
+ this.buffers.push(chunk);
60
+ });
61
+ inputStream.once('end', () => resolve());
62
+ inputStream.once('error', (error) => reject(error));
63
+ });
64
+ }
65
+ }
66
+ }
67
+ exports.ZipWriter = ZipWriter;
68
+ //# sourceMappingURL=zipWriter.js.map
@@ -1,8 +1,8 @@
1
1
  /// <reference types="node" />
2
2
  import * as http from 'http';
3
+ import { JwtOAuth2Config } from 'jsforce';
3
4
  import { AsyncCreatable } from '@salesforce/kit';
4
- import { OAuth2Options } from 'jsforce';
5
- import { AuthInfo } from './org/authInfo';
5
+ import { AuthInfo } from './org';
6
6
  /**
7
7
  * Handles the creation of a web server for web based login flows.
8
8
  *
@@ -26,6 +26,7 @@ export declare class WebOAuthServer extends AsyncCreatable<WebOAuthServer.Option
26
26
  private webServer;
27
27
  private oauth2;
28
28
  private oauthConfig;
29
+ private oauthError;
29
30
  constructor(options: WebOAuthServer.Options);
30
31
  /**
31
32
  * Returns the configured oauthLocalPort or the WebOAuthServer.DEFAULT_PORT
@@ -80,12 +81,14 @@ export declare class WebOAuthServer extends AsyncCreatable<WebOAuthServer.Option
80
81
  }
81
82
  export declare namespace WebOAuthServer {
82
83
  interface Options {
83
- oauthConfig: OAuth2Options;
84
+ oauthConfig: JwtOAuth2Config;
84
85
  }
85
86
  type Request = http.IncomingMessage & {
86
87
  query: {
87
88
  code: string;
88
89
  state: string;
90
+ error?: string;
91
+ error_description?: string;
89
92
  };
90
93
  };
91
94
  }
@@ -99,6 +102,7 @@ export declare class WebServer extends AsyncCreatable<WebServer.Options> {
99
102
  host: string;
100
103
  private logger;
101
104
  private sockets;
105
+ private redirectStatus;
102
106
  constructor(options: WebServer.Options);
103
107
  /**
104
108
  * Starts the http server after checking that the port is open
@@ -111,7 +115,7 @@ export declare class WebServer extends AsyncCreatable<WebServer.Options> {
111
115
  /**
112
116
  * sends a response error.
113
117
  *
114
- * @param statusCode he statusCode for the response.
118
+ * @param status the statusCode for the response.
115
119
  * @param message the message for the http body.
116
120
  * @param response the response to write the error to.
117
121
  */
@@ -119,7 +123,7 @@ export declare class WebServer extends AsyncCreatable<WebServer.Options> {
119
123
  /**
120
124
  * sends a response redirect.
121
125
  *
122
- * @param statusCode the statusCode for the response.
126
+ * @param status the statusCode for the response.
123
127
  * @param url the url to redirect to.
124
128
  * @param response the response to write the redirect to.
125
129
  */
@@ -127,11 +131,20 @@ export declare class WebServer extends AsyncCreatable<WebServer.Options> {
127
131
  /**
128
132
  * sends a response to the browser reporting an error.
129
133
  *
130
- * @param error the error
131
- * @param response the response to write the redirect to.
134
+ * @param error the oauth error
135
+ * @param response the HTTP response.
132
136
  */
133
137
  reportError(error: Error, response: http.ServerResponse): void;
138
+ /**
139
+ * sends a response to the browser reporting the success.
140
+ *
141
+ * @param response the HTTP response.
142
+ */
143
+ reportSuccess(response: http.ServerResponse): void;
144
+ handleSuccess(response: http.ServerResponse): Promise<void>;
145
+ handleError(response: http.ServerResponse): Promise<void>;
134
146
  protected init(): Promise<void>;
147
+ private handleRedirect;
135
148
  /**
136
149
  * Make sure we can't open a socket on the localhost/host port. It's important because we don't want to send
137
150
  * auth tokens to a random strange port listener. We want to make sure we can startup our server first.