@backstage/integration 1.18.1 → 1.18.2

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,33 @@
1
1
  # @backstage/integration
2
2
 
3
+ ## 1.18.2
4
+
5
+ ### Patch Changes
6
+
7
+ - fa255f5: Support for Bitbucket Cloud's API token was added as `appPassword` is deprecated (no new creation from September 9, 2025) and will be removed on June 9, 2026.
8
+
9
+ API token usage example:
10
+
11
+ ```yaml
12
+ integrations:
13
+ bitbucketCloud:
14
+ - username: user@domain.com
15
+ token: my-token
16
+ ```
17
+
18
+ - 05f60e1: Refactored constructor parameter properties to explicit property declarations for compatibility with TypeScript's `erasableSyntaxOnly` setting. This internal refactoring maintains all existing functionality while ensuring TypeScript compilation compatibility.
19
+ - Updated dependencies
20
+ - @backstage/config@1.3.6
21
+
22
+ ## 1.18.2-next.0
23
+
24
+ ### Patch Changes
25
+
26
+ - 05f60e1: Refactored constructor parameter properties to explicit property declarations for compatibility with TypeScript's `erasableSyntaxOnly` setting. This internal refactoring maintains all existing functionality while ensuring TypeScript compilation compatibility.
27
+ - Updated dependencies
28
+ - @backstage/config@1.3.6-next.0
29
+ - @backstage/errors@1.2.7
30
+
3
31
  ## 1.18.1
4
32
 
5
33
  ### Patch Changes
package/config.d.ts CHANGED
@@ -175,11 +175,17 @@ export interface Config {
175
175
  * @visibility secret
176
176
  */
177
177
  username: string;
178
+ /**
179
+ * Token used to authenticate requests.
180
+ * @visibility secret
181
+ */
182
+ token?: string;
178
183
  /**
179
184
  * Bitbucket Cloud app password used to authenticate requests.
180
185
  * @visibility secret
186
+ * @deprecated Use `token` instead.
181
187
  */
182
- appPassword: string;
188
+ appPassword?: string;
183
189
  /**
184
190
  * PGP signing key for signing commits.
185
191
  * @visibility secret
@@ -6,12 +6,19 @@ function readBitbucketCloudIntegrationConfig(config) {
6
6
  const host = BITBUCKET_CLOUD_HOST;
7
7
  const apiBaseUrl = BITBUCKET_CLOUD_API_BASE_URL;
8
8
  const username = config.getString("username");
9
- const appPassword = config.getString("appPassword")?.trim();
9
+ const appPassword = config.getOptionalString("appPassword")?.trim();
10
+ const token = config.getOptionalString("token");
11
+ if (!token && !appPassword) {
12
+ throw new Error(
13
+ `Bitbucket Cloud integration must be configured with as username and either a token or an appPassword.`
14
+ );
15
+ }
10
16
  return {
11
17
  host,
12
18
  apiBaseUrl,
13
19
  username,
14
20
  appPassword,
21
+ token,
15
22
  commitSigningKey: config.getOptionalString("commitSigningKey")
16
23
  };
17
24
  }
@@ -1 +1 @@
1
- {"version":3,"file":"config.cjs.js","sources":["../../src/bitbucketCloud/config.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\n\nconst BITBUCKET_CLOUD_HOST = 'bitbucket.org';\nconst BITBUCKET_CLOUD_API_BASE_URL = 'https://api.bitbucket.org/2.0';\n\n/**\n * The configuration parameters for a single Bitbucket Cloud API provider.\n *\n * @public\n */\nexport type BitbucketCloudIntegrationConfig = {\n /**\n * Constant. bitbucket.org\n */\n host: string;\n\n /**\n * Constant. https://api.bitbucket.org/2.0\n */\n apiBaseUrl: string;\n\n /**\n * The username to use for requests to Bitbucket Cloud (bitbucket.org).\n */\n username?: string;\n\n /**\n * Authentication with Bitbucket Cloud (bitbucket.org) is done using app passwords.\n *\n * See https://support.atlassian.com/bitbucket-cloud/docs/app-passwords/\n */\n appPassword?: string;\n\n /**\n * The access token to use for requests to Bitbucket Cloud (bitbucket.org).\n */\n token?: string;\n\n /** PGP private key for signing commits. */\n commitSigningKey?: string;\n};\n\n/**\n * Reads a single Bitbucket Cloud integration config.\n *\n * @param config - The config object of a single integration\n * @public\n */\nexport function readBitbucketCloudIntegrationConfig(\n config: Config,\n): BitbucketCloudIntegrationConfig {\n const host = BITBUCKET_CLOUD_HOST;\n const apiBaseUrl = BITBUCKET_CLOUD_API_BASE_URL;\n // If config is provided, we assume authenticated access is desired\n // (as the anonymous one is provided by default).\n const username = config.getString('username');\n const appPassword = config.getString('appPassword')?.trim();\n\n return {\n host,\n apiBaseUrl,\n username,\n appPassword,\n commitSigningKey: config.getOptionalString('commitSigningKey'),\n };\n}\n\n/**\n * Reads a set of Bitbucket Cloud integration configs,\n * and inserts one for public Bitbucket Cloud if none specified.\n *\n * @param configs - All of the integration config objects\n * @public\n */\nexport function readBitbucketCloudIntegrationConfigs(\n configs: Config[],\n): BitbucketCloudIntegrationConfig[] {\n // First read all the explicit integrations\n const result = configs.map(readBitbucketCloudIntegrationConfig);\n\n // If no explicit bitbucket.org integration was added,\n // put one in the list as a convenience\n if (result.length === 0) {\n result.push({\n host: BITBUCKET_CLOUD_HOST,\n apiBaseUrl: BITBUCKET_CLOUD_API_BASE_URL,\n });\n }\n\n return result;\n}\n"],"names":[],"mappings":";;AAkBA,MAAM,oBAAA,GAAuB,eAAA;AAC7B,MAAM,4BAAA,GAA+B,+BAAA;AA6C9B,SAAS,oCACd,MAAA,EACiC;AACjC,EAAA,MAAM,IAAA,GAAO,oBAAA;AACb,EAAA,MAAM,UAAA,GAAa,4BAAA;AAGnB,EAAA,MAAM,QAAA,GAAW,MAAA,CAAO,SAAA,CAAU,UAAU,CAAA;AAC5C,EAAA,MAAM,WAAA,GAAc,MAAA,CAAO,SAAA,CAAU,aAAa,GAAG,IAAA,EAAK;AAE1D,EAAA,OAAO;AAAA,IACL,IAAA;AAAA,IACA,UAAA;AAAA,IACA,QAAA;AAAA,IACA,WAAA;AAAA,IACA,gBAAA,EAAkB,MAAA,CAAO,iBAAA,CAAkB,kBAAkB;AAAA,GAC/D;AACF;AASO,SAAS,qCACd,OAAA,EACmC;AAEnC,EAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,GAAA,CAAI,mCAAmC,CAAA;AAI9D,EAAA,IAAI,MAAA,CAAO,WAAW,CAAA,EAAG;AACvB,IAAA,MAAA,CAAO,IAAA,CAAK;AAAA,MACV,IAAA,EAAM,oBAAA;AAAA,MACN,UAAA,EAAY;AAAA,KACb,CAAA;AAAA,EACH;AAEA,EAAA,OAAO,MAAA;AACT;;;;;"}
1
+ {"version":3,"file":"config.cjs.js","sources":["../../src/bitbucketCloud/config.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\n\nconst BITBUCKET_CLOUD_HOST = 'bitbucket.org';\nconst BITBUCKET_CLOUD_API_BASE_URL = 'https://api.bitbucket.org/2.0';\n\n/**\n * The configuration parameters for a single Bitbucket Cloud API provider.\n *\n * @public\n */\nexport type BitbucketCloudIntegrationConfig = {\n /**\n * Constant. bitbucket.org\n */\n host: string;\n\n /**\n * Constant. https://api.bitbucket.org/2.0\n */\n apiBaseUrl: string;\n\n /**\n * The username to use for requests to Bitbucket Cloud (bitbucket.org).\n */\n username?: string;\n\n /**\n * Authentication with Bitbucket Cloud (bitbucket.org) is done using app passwords.\n *\n * See https://support.atlassian.com/bitbucket-cloud/docs/app-passwords/\n */\n appPassword?: string;\n\n /**\n * The access token to use for requests to Bitbucket Cloud (bitbucket.org).\n *\n * See https://support.atlassian.com/bitbucket-cloud/docs/api-tokens/\n */\n token?: string;\n\n /** PGP private key for signing commits. */\n commitSigningKey?: string;\n};\n\n/**\n * Reads a single Bitbucket Cloud integration config.\n *\n * @param config - The config object of a single integration\n * @public\n */\nexport function readBitbucketCloudIntegrationConfig(\n config: Config,\n): BitbucketCloudIntegrationConfig {\n const host = BITBUCKET_CLOUD_HOST;\n const apiBaseUrl = BITBUCKET_CLOUD_API_BASE_URL;\n // If config is provided, we assume authenticated access is desired\n // (as the anonymous one is provided by default).\n const username = config.getString('username');\n // TODO: appPassword can be removed once fully\n // deprecated by BitBucket on 9th June 2026.\n const appPassword = config.getOptionalString('appPassword')?.trim();\n const token = config.getOptionalString('token');\n\n if (!token && !appPassword) {\n throw new Error(\n `Bitbucket Cloud integration must be configured with as username and either a token or an appPassword.`,\n );\n }\n\n return {\n host,\n apiBaseUrl,\n username,\n appPassword,\n token,\n commitSigningKey: config.getOptionalString('commitSigningKey'),\n };\n}\n\n/**\n * Reads a set of Bitbucket Cloud integration configs,\n * and inserts one for public Bitbucket Cloud if none specified.\n *\n * @param configs - All of the integration config objects\n * @public\n */\nexport function readBitbucketCloudIntegrationConfigs(\n configs: Config[],\n): BitbucketCloudIntegrationConfig[] {\n // First read all the explicit integrations\n const result = configs.map(readBitbucketCloudIntegrationConfig);\n\n // If no explicit bitbucket.org integration was added,\n // put one in the list as a convenience\n if (result.length === 0) {\n result.push({\n host: BITBUCKET_CLOUD_HOST,\n apiBaseUrl: BITBUCKET_CLOUD_API_BASE_URL,\n });\n }\n\n return result;\n}\n"],"names":[],"mappings":";;AAkBA,MAAM,oBAAA,GAAuB,eAAA;AAC7B,MAAM,4BAAA,GAA+B,+BAAA;AA+C9B,SAAS,oCACd,MAAA,EACiC;AACjC,EAAA,MAAM,IAAA,GAAO,oBAAA;AACb,EAAA,MAAM,UAAA,GAAa,4BAAA;AAGnB,EAAA,MAAM,QAAA,GAAW,MAAA,CAAO,SAAA,CAAU,UAAU,CAAA;AAG5C,EAAA,MAAM,WAAA,GAAc,MAAA,CAAO,iBAAA,CAAkB,aAAa,GAAG,IAAA,EAAK;AAClE,EAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,iBAAA,CAAkB,OAAO,CAAA;AAE9C,EAAA,IAAI,CAAC,KAAA,IAAS,CAAC,WAAA,EAAa;AAC1B,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,qGAAA;AAAA,KACF;AAAA,EACF;AAEA,EAAA,OAAO;AAAA,IACL,IAAA;AAAA,IACA,UAAA;AAAA,IACA,QAAA;AAAA,IACA,WAAA;AAAA,IACA,KAAA;AAAA,IACA,gBAAA,EAAkB,MAAA,CAAO,iBAAA,CAAkB,kBAAkB;AAAA,GAC/D;AACF;AASO,SAAS,qCACd,OAAA,EACmC;AAEnC,EAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,GAAA,CAAI,mCAAmC,CAAA;AAI9D,EAAA,IAAI,MAAA,CAAO,WAAW,CAAA,EAAG;AACvB,IAAA,MAAA,CAAO,IAAA,CAAK;AAAA,MACV,IAAA,EAAM,oBAAA;AAAA,MACN,UAAA,EAAY;AAAA,KACb,CAAA;AAAA,EACH;AAEA,EAAA,OAAO,MAAA;AACT;;;;;"}
@@ -4,12 +4,19 @@ function readBitbucketCloudIntegrationConfig(config) {
4
4
  const host = BITBUCKET_CLOUD_HOST;
5
5
  const apiBaseUrl = BITBUCKET_CLOUD_API_BASE_URL;
6
6
  const username = config.getString("username");
7
- const appPassword = config.getString("appPassword")?.trim();
7
+ const appPassword = config.getOptionalString("appPassword")?.trim();
8
+ const token = config.getOptionalString("token");
9
+ if (!token && !appPassword) {
10
+ throw new Error(
11
+ `Bitbucket Cloud integration must be configured with as username and either a token or an appPassword.`
12
+ );
13
+ }
8
14
  return {
9
15
  host,
10
16
  apiBaseUrl,
11
17
  username,
12
18
  appPassword,
19
+ token,
13
20
  commitSigningKey: config.getOptionalString("commitSigningKey")
14
21
  };
15
22
  }
@@ -1 +1 @@
1
- {"version":3,"file":"config.esm.js","sources":["../../src/bitbucketCloud/config.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\n\nconst BITBUCKET_CLOUD_HOST = 'bitbucket.org';\nconst BITBUCKET_CLOUD_API_BASE_URL = 'https://api.bitbucket.org/2.0';\n\n/**\n * The configuration parameters for a single Bitbucket Cloud API provider.\n *\n * @public\n */\nexport type BitbucketCloudIntegrationConfig = {\n /**\n * Constant. bitbucket.org\n */\n host: string;\n\n /**\n * Constant. https://api.bitbucket.org/2.0\n */\n apiBaseUrl: string;\n\n /**\n * The username to use for requests to Bitbucket Cloud (bitbucket.org).\n */\n username?: string;\n\n /**\n * Authentication with Bitbucket Cloud (bitbucket.org) is done using app passwords.\n *\n * See https://support.atlassian.com/bitbucket-cloud/docs/app-passwords/\n */\n appPassword?: string;\n\n /**\n * The access token to use for requests to Bitbucket Cloud (bitbucket.org).\n */\n token?: string;\n\n /** PGP private key for signing commits. */\n commitSigningKey?: string;\n};\n\n/**\n * Reads a single Bitbucket Cloud integration config.\n *\n * @param config - The config object of a single integration\n * @public\n */\nexport function readBitbucketCloudIntegrationConfig(\n config: Config,\n): BitbucketCloudIntegrationConfig {\n const host = BITBUCKET_CLOUD_HOST;\n const apiBaseUrl = BITBUCKET_CLOUD_API_BASE_URL;\n // If config is provided, we assume authenticated access is desired\n // (as the anonymous one is provided by default).\n const username = config.getString('username');\n const appPassword = config.getString('appPassword')?.trim();\n\n return {\n host,\n apiBaseUrl,\n username,\n appPassword,\n commitSigningKey: config.getOptionalString('commitSigningKey'),\n };\n}\n\n/**\n * Reads a set of Bitbucket Cloud integration configs,\n * and inserts one for public Bitbucket Cloud if none specified.\n *\n * @param configs - All of the integration config objects\n * @public\n */\nexport function readBitbucketCloudIntegrationConfigs(\n configs: Config[],\n): BitbucketCloudIntegrationConfig[] {\n // First read all the explicit integrations\n const result = configs.map(readBitbucketCloudIntegrationConfig);\n\n // If no explicit bitbucket.org integration was added,\n // put one in the list as a convenience\n if (result.length === 0) {\n result.push({\n host: BITBUCKET_CLOUD_HOST,\n apiBaseUrl: BITBUCKET_CLOUD_API_BASE_URL,\n });\n }\n\n return result;\n}\n"],"names":[],"mappings":"AAkBA,MAAM,oBAAA,GAAuB,eAAA;AAC7B,MAAM,4BAAA,GAA+B,+BAAA;AA6C9B,SAAS,oCACd,MAAA,EACiC;AACjC,EAAA,MAAM,IAAA,GAAO,oBAAA;AACb,EAAA,MAAM,UAAA,GAAa,4BAAA;AAGnB,EAAA,MAAM,QAAA,GAAW,MAAA,CAAO,SAAA,CAAU,UAAU,CAAA;AAC5C,EAAA,MAAM,WAAA,GAAc,MAAA,CAAO,SAAA,CAAU,aAAa,GAAG,IAAA,EAAK;AAE1D,EAAA,OAAO;AAAA,IACL,IAAA;AAAA,IACA,UAAA;AAAA,IACA,QAAA;AAAA,IACA,WAAA;AAAA,IACA,gBAAA,EAAkB,MAAA,CAAO,iBAAA,CAAkB,kBAAkB;AAAA,GAC/D;AACF;AASO,SAAS,qCACd,OAAA,EACmC;AAEnC,EAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,GAAA,CAAI,mCAAmC,CAAA;AAI9D,EAAA,IAAI,MAAA,CAAO,WAAW,CAAA,EAAG;AACvB,IAAA,MAAA,CAAO,IAAA,CAAK;AAAA,MACV,IAAA,EAAM,oBAAA;AAAA,MACN,UAAA,EAAY;AAAA,KACb,CAAA;AAAA,EACH;AAEA,EAAA,OAAO,MAAA;AACT;;;;"}
1
+ {"version":3,"file":"config.esm.js","sources":["../../src/bitbucketCloud/config.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\n\nconst BITBUCKET_CLOUD_HOST = 'bitbucket.org';\nconst BITBUCKET_CLOUD_API_BASE_URL = 'https://api.bitbucket.org/2.0';\n\n/**\n * The configuration parameters for a single Bitbucket Cloud API provider.\n *\n * @public\n */\nexport type BitbucketCloudIntegrationConfig = {\n /**\n * Constant. bitbucket.org\n */\n host: string;\n\n /**\n * Constant. https://api.bitbucket.org/2.0\n */\n apiBaseUrl: string;\n\n /**\n * The username to use for requests to Bitbucket Cloud (bitbucket.org).\n */\n username?: string;\n\n /**\n * Authentication with Bitbucket Cloud (bitbucket.org) is done using app passwords.\n *\n * See https://support.atlassian.com/bitbucket-cloud/docs/app-passwords/\n */\n appPassword?: string;\n\n /**\n * The access token to use for requests to Bitbucket Cloud (bitbucket.org).\n *\n * See https://support.atlassian.com/bitbucket-cloud/docs/api-tokens/\n */\n token?: string;\n\n /** PGP private key for signing commits. */\n commitSigningKey?: string;\n};\n\n/**\n * Reads a single Bitbucket Cloud integration config.\n *\n * @param config - The config object of a single integration\n * @public\n */\nexport function readBitbucketCloudIntegrationConfig(\n config: Config,\n): BitbucketCloudIntegrationConfig {\n const host = BITBUCKET_CLOUD_HOST;\n const apiBaseUrl = BITBUCKET_CLOUD_API_BASE_URL;\n // If config is provided, we assume authenticated access is desired\n // (as the anonymous one is provided by default).\n const username = config.getString('username');\n // TODO: appPassword can be removed once fully\n // deprecated by BitBucket on 9th June 2026.\n const appPassword = config.getOptionalString('appPassword')?.trim();\n const token = config.getOptionalString('token');\n\n if (!token && !appPassword) {\n throw new Error(\n `Bitbucket Cloud integration must be configured with as username and either a token or an appPassword.`,\n );\n }\n\n return {\n host,\n apiBaseUrl,\n username,\n appPassword,\n token,\n commitSigningKey: config.getOptionalString('commitSigningKey'),\n };\n}\n\n/**\n * Reads a set of Bitbucket Cloud integration configs,\n * and inserts one for public Bitbucket Cloud if none specified.\n *\n * @param configs - All of the integration config objects\n * @public\n */\nexport function readBitbucketCloudIntegrationConfigs(\n configs: Config[],\n): BitbucketCloudIntegrationConfig[] {\n // First read all the explicit integrations\n const result = configs.map(readBitbucketCloudIntegrationConfig);\n\n // If no explicit bitbucket.org integration was added,\n // put one in the list as a convenience\n if (result.length === 0) {\n result.push({\n host: BITBUCKET_CLOUD_HOST,\n apiBaseUrl: BITBUCKET_CLOUD_API_BASE_URL,\n });\n }\n\n return result;\n}\n"],"names":[],"mappings":"AAkBA,MAAM,oBAAA,GAAuB,eAAA;AAC7B,MAAM,4BAAA,GAA+B,+BAAA;AA+C9B,SAAS,oCACd,MAAA,EACiC;AACjC,EAAA,MAAM,IAAA,GAAO,oBAAA;AACb,EAAA,MAAM,UAAA,GAAa,4BAAA;AAGnB,EAAA,MAAM,QAAA,GAAW,MAAA,CAAO,SAAA,CAAU,UAAU,CAAA;AAG5C,EAAA,MAAM,WAAA,GAAc,MAAA,CAAO,iBAAA,CAAkB,aAAa,GAAG,IAAA,EAAK;AAClE,EAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,iBAAA,CAAkB,OAAO,CAAA;AAE9C,EAAA,IAAI,CAAC,KAAA,IAAS,CAAC,WAAA,EAAa;AAC1B,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,qGAAA;AAAA,KACF;AAAA,EACF;AAEA,EAAA,OAAO;AAAA,IACL,IAAA;AAAA,IACA,UAAA;AAAA,IACA,QAAA;AAAA,IACA,WAAA;AAAA,IACA,KAAA;AAAA,IACA,gBAAA,EAAkB,MAAA,CAAO,iBAAA,CAAkB,kBAAkB;AAAA,GAC/D;AACF;AASO,SAAS,qCACd,OAAA,EACmC;AAEnC,EAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,GAAA,CAAI,mCAAmC,CAAA;AAI9D,EAAA,IAAI,MAAA,CAAO,WAAW,CAAA,EAAG;AACvB,IAAA,MAAA,CAAO,IAAA,CAAK;AAAA,MACV,IAAA,EAAM,oBAAA;AAAA,MACN,UAAA,EAAY;AAAA,KACb,CAAA;AAAA,EACH;AAEA,EAAA,OAAO,MAAA;AACT;;;;"}
@@ -59,16 +59,14 @@ function getBitbucketCloudFileFetchUrl(url, config) {
59
59
  }
60
60
  function getBitbucketCloudRequestOptions(config) {
61
61
  const headers = {};
62
- if (config.username && config.appPassword) {
62
+ if (config.username && (config.token ?? config.appPassword)) {
63
63
  const buffer = Buffer.from(
64
- `${config.username}:${config.appPassword}`,
64
+ `${config.username}:${config.token ?? config.appPassword}`,
65
65
  "utf8"
66
66
  );
67
67
  headers.Authorization = `Basic ${buffer.toString("base64")}`;
68
68
  }
69
- return {
70
- headers
71
- };
69
+ return { headers };
72
70
  }
73
71
 
74
72
  exports.getBitbucketCloudDefaultBranch = getBitbucketCloudDefaultBranch;
@@ -1 +1 @@
1
- {"version":3,"file":"core.cjs.js","sources":["../../src/bitbucketCloud/core.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport fetch from 'cross-fetch';\nimport parseGitUrl from 'git-url-parse';\nimport { BitbucketCloudIntegrationConfig } from './config';\n\n/**\n * Given a URL pointing to a path on a provider, returns the default branch.\n *\n * @param url - A URL pointing to a path\n * @param config - The relevant provider config\n * @public\n */\nexport async function getBitbucketCloudDefaultBranch(\n url: string,\n config: BitbucketCloudIntegrationConfig,\n): Promise<string> {\n const { name: repoName, owner: project } = parseGitUrl(url);\n\n const branchUrl = `${config.apiBaseUrl}/repositories/${project}/${repoName}`;\n const response = await fetch(\n branchUrl,\n getBitbucketCloudRequestOptions(config),\n );\n\n if (!response.ok) {\n const message = `Failed to retrieve default branch from ${branchUrl}, ${response.status} ${response.statusText}`;\n throw new Error(message);\n }\n\n const repoInfo = await response.json();\n const defaultBranch = repoInfo.mainbranch.name;\n if (!defaultBranch) {\n throw new Error(\n `Failed to read default branch from ${branchUrl}. ` +\n `Response ${response.status} ${response.json()}`,\n );\n }\n return defaultBranch;\n}\n\n/**\n * Given a URL pointing to a path on a provider, returns a URL that is suitable\n * for downloading the subtree.\n *\n * @param url - A URL pointing to a path\n * @param config - The relevant provider config\n * @public\n */\nexport async function getBitbucketCloudDownloadUrl(\n url: string,\n config: BitbucketCloudIntegrationConfig,\n): Promise<string> {\n const {\n name: repoName,\n owner: project,\n ref,\n protocol,\n resource,\n } = parseGitUrl(url);\n\n let branch = ref;\n if (!branch) {\n branch = await getBitbucketCloudDefaultBranch(url, config);\n }\n return `${protocol}://${resource}/${project}/${repoName}/get/${branch}.tar.gz`;\n}\n\n/**\n * Given a URL pointing to a file on a provider, returns a URL that is suitable\n * for fetching the contents of the data.\n *\n * @remarks\n *\n * Converts\n * from: https://bitbucket.org/orgname/reponame/src/master/file.yaml\n * to: https://api.bitbucket.org/2.0/repositories/orgname/reponame/src/master/file.yaml\n *\n * @param url - A URL pointing to a file\n * @param config - The relevant provider config\n * @public\n */\nexport function getBitbucketCloudFileFetchUrl(\n url: string,\n config: BitbucketCloudIntegrationConfig,\n): string {\n try {\n const { owner, name, ref, filepathtype, filepath } = parseGitUrl(url);\n if (!owner || !name || (filepathtype !== 'src' && filepathtype !== 'raw')) {\n throw new Error('Invalid Bitbucket Cloud URL or file path');\n }\n\n const pathWithoutSlash = filepath.replace(/^\\//, '');\n\n if (!ref) {\n throw new Error('Invalid Bitbucket Cloud URL or file path');\n }\n return `${config.apiBaseUrl}/repositories/${owner}/${name}/src/${ref}/${pathWithoutSlash}`;\n } catch (e) {\n throw new Error(`Incorrect URL: ${url}, ${e}`);\n }\n}\n\n/**\n * Gets the request options necessary to make requests to a given provider.\n *\n * @param config - The relevant provider config\n * @public\n */\nexport function getBitbucketCloudRequestOptions(\n config: BitbucketCloudIntegrationConfig,\n): { headers: Record<string, string> } {\n const headers: Record<string, string> = {};\n\n if (config.username && config.appPassword) {\n const buffer = Buffer.from(\n `${config.username}:${config.appPassword}`,\n 'utf8',\n );\n headers.Authorization = `Basic ${buffer.toString('base64')}`;\n }\n\n return {\n headers,\n };\n}\n"],"names":["parseGitUrl","fetch"],"mappings":";;;;;;;;;;AA2BA,eAAsB,8BAAA,CACpB,KACA,MAAA,EACiB;AACjB,EAAA,MAAM,EAAE,IAAA,EAAM,QAAA,EAAU,OAAO,OAAA,EAAQ,GAAIA,6BAAY,GAAG,CAAA;AAE1D,EAAA,MAAM,YAAY,CAAA,EAAG,MAAA,CAAO,UAAU,CAAA,cAAA,EAAiB,OAAO,IAAI,QAAQ,CAAA,CAAA;AAC1E,EAAA,MAAM,WAAW,MAAMC,sBAAA;AAAA,IACrB,SAAA;AAAA,IACA,gCAAgC,MAAM;AAAA,GACxC;AAEA,EAAA,IAAI,CAAC,SAAS,EAAA,EAAI;AAChB,IAAA,MAAM,OAAA,GAAU,0CAA0C,SAAS,CAAA,EAAA,EAAK,SAAS,MAAM,CAAA,CAAA,EAAI,SAAS,UAAU,CAAA,CAAA;AAC9G,IAAA,MAAM,IAAI,MAAM,OAAO,CAAA;AAAA,EACzB;AAEA,EAAA,MAAM,QAAA,GAAW,MAAM,QAAA,CAAS,IAAA,EAAK;AACrC,EAAA,MAAM,aAAA,GAAgB,SAAS,UAAA,CAAW,IAAA;AAC1C,EAAA,IAAI,CAAC,aAAA,EAAe;AAClB,IAAA,MAAM,IAAI,KAAA;AAA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I,CAAA,KAAA,EAAQ,GAAG,CAAA,CAAA,EAAI,gBAAgB,CAAA,CAAA;AAAA,EAC1F,SAAS,CAAA,EAAG;AACV,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,eAAA,EAAkB,GAAG,CAAA,EAAA,EAAK,CAAC,CAAA,CAAE,CAAA;AAAA,EAC/C;AACF;AAQO,SAAS,gCACd,MAAA,EACqC;AACrC,EAAA,MAAM,UAAkC,EAAC;AAEzC,EAAA,IAAI,MAAA,CAAO,QAAA,IAAY,MAAA,CAAO,WAAA,EAAa;AACzC,IAAA,MAAM,SAAS,MAAA,CAAO,IAAA;AAAA,MACpB,CAAA,EAAG,MAAA,CAAO,QAAQ,CAAA,CAAA,EAAI,OAAO,WAAW,CAAA,CAAA;AAAA,MACxC;AAAA,KACF;AACA,IAAA,OAAA,CAAQ,aAAA,GAAgB,CAAA,MAAA,EAAS,MAAA,CAAO,QAAA,CAAS,QAAQ,CAAC,CAAA,CAAA;AAAA,EAC5D;AAEA,EAAA,OAAO;AAAA,IACL;AAAA,GACF;AACF;;;;;;;"}
1
+ {"version":3,"file":"core.cjs.js","sources":["../../src/bitbucketCloud/core.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport fetch from 'cross-fetch';\nimport parseGitUrl from 'git-url-parse';\nimport { BitbucketCloudIntegrationConfig } from './config';\n\n/**\n * Given a URL pointing to a path on a provider, returns the default branch.\n *\n * @param url - A URL pointing to a path\n * @param config - The relevant provider config\n * @public\n */\nexport async function getBitbucketCloudDefaultBranch(\n url: string,\n config: BitbucketCloudIntegrationConfig,\n): Promise<string> {\n const { name: repoName, owner: project } = parseGitUrl(url);\n\n const branchUrl = `${config.apiBaseUrl}/repositories/${project}/${repoName}`;\n const response = await fetch(\n branchUrl,\n getBitbucketCloudRequestOptions(config),\n );\n\n if (!response.ok) {\n const message = `Failed to retrieve default branch from ${branchUrl}, ${response.status} ${response.statusText}`;\n throw new Error(message);\n }\n\n const repoInfo = await response.json();\n const defaultBranch = repoInfo.mainbranch.name;\n if (!defaultBranch) {\n throw new Error(\n `Failed to read default branch from ${branchUrl}. ` +\n `Response ${response.status} ${response.json()}`,\n );\n }\n return defaultBranch;\n}\n\n/**\n * Given a URL pointing to a path on a provider, returns a URL that is suitable\n * for downloading the subtree.\n *\n * @param url - A URL pointing to a path\n * @param config - The relevant provider config\n * @public\n */\nexport async function getBitbucketCloudDownloadUrl(\n url: string,\n config: BitbucketCloudIntegrationConfig,\n): Promise<string> {\n const {\n name: repoName,\n owner: project,\n ref,\n protocol,\n resource,\n } = parseGitUrl(url);\n\n let branch = ref;\n if (!branch) {\n branch = await getBitbucketCloudDefaultBranch(url, config);\n }\n return `${protocol}://${resource}/${project}/${repoName}/get/${branch}.tar.gz`;\n}\n\n/**\n * Given a URL pointing to a file on a provider, returns a URL that is suitable\n * for fetching the contents of the data.\n *\n * @remarks\n *\n * Converts\n * from: https://bitbucket.org/orgname/reponame/src/master/file.yaml\n * to: https://api.bitbucket.org/2.0/repositories/orgname/reponame/src/master/file.yaml\n *\n * @param url - A URL pointing to a file\n * @param config - The relevant provider config\n * @public\n */\nexport function getBitbucketCloudFileFetchUrl(\n url: string,\n config: BitbucketCloudIntegrationConfig,\n): string {\n try {\n const { owner, name, ref, filepathtype, filepath } = parseGitUrl(url);\n if (!owner || !name || (filepathtype !== 'src' && filepathtype !== 'raw')) {\n throw new Error('Invalid Bitbucket Cloud URL or file path');\n }\n\n const pathWithoutSlash = filepath.replace(/^\\//, '');\n\n if (!ref) {\n throw new Error('Invalid Bitbucket Cloud URL or file path');\n }\n return `${config.apiBaseUrl}/repositories/${owner}/${name}/src/${ref}/${pathWithoutSlash}`;\n } catch (e) {\n throw new Error(`Incorrect URL: ${url}, ${e}`);\n }\n}\n\n/**\n * Gets the request options necessary to make requests to a given provider.\n * Returns headers for authenticating with Bitbucket Cloud.\n * Supports both username/token and username/appPassword auth.\n *\n * @param config - The relevant provider config\n * @public\n */\nexport function getBitbucketCloudRequestOptions(\n config: BitbucketCloudIntegrationConfig,\n): {\n headers: Record<string, string>;\n} {\n const headers: Record<string, string> = {};\n\n // TODO: appPassword can be removed once fully\n // deprecated by BitBucket on 9th June 2026.\n if (config.username && (config.token ?? config.appPassword)) {\n const buffer = Buffer.from(\n `${config.username}:${config.token ?? config.appPassword}`,\n 'utf8',\n );\n headers.Authorization = `Basic ${buffer.toString('base64')}`;\n }\n\n return { headers };\n}\n"],"names":["parseGitUrl","fetch"],"mappings":";;;;;;;;;;AA2BA,eAAsB,8BAAA,CACpB,KACA,MAAA,EACiB;AACjB,EAAA,MAAM,EAAE,IAAA,EAAM,QAAA,EAAU,OAAO,OAAA,EAAQ,GAAIA,6BAAY,GAAG,CAAA;AAE1D,EAAA,MAAM,YAAY,CAAA,EAAG,MAAA,CAAO,UAAU,CAAA,cAAA,EAAiB,OAAO,IAAI,QAAQ,CAAA,CAAA;AAC1E,EAAA,MAAM,WAAW,MAAMC,sBAAA;AAAA,IACrB,SAAA;AAAA,IACA,gCAAgC,MAAM;AAAA,GACxC;AAEA,EAAA,IAAI,CAAC,SAAS,EAAA,EAAI;AAChB,IAAA,MAAM,OAAA,GAAU,0CAA0C,SAAS,CAAA,EAAA,EAAK,SAAS,MAAM,CAAA,CAAA,EAAI,SAAS,UAAU,CAAA,CAAA;AAC9G,IAAA,MAAM,IAAI,MAAM,OAAO,CAAA;AAAA,EACzB;AAEA,EAAA,MAAM,QAAA,GAAW,MAAM,QAAA,CAAS,IAAA,EAAK;AACrC,EAAA,MAAM,aAAA,GAAgB,SAAS,UAAA,CAAW,IAAA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,OAAO,CAAA,EAAG,MAAA,CAAO,UAAU,CAAA,cAAA,EAAiB,KAAK,IAAI,IAAI,CAAA,KAAA,EAAQ,GAAG,CAAA,CAAA,EAAI,gBAAgB,CAAA,CAAA;AAAA,EAC1F,SAAS,CAAA,EAAG;AACV,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,eAAA,EAAkB,GAAG,CAAA,EAAA,EAAK,CAAC,CAAA,CAAE,CAAA;AAAA,EAC/C;AACF;AAUO,SAAS,gCACd,MAAA,EAGA;AACA,EAAA,MAAM,UAAkC,EAAC;AAIzC,EAAA,IAAI,MAAA,CAAO,QAAA,KAAa,MAAA,CAAO,KAAA,IAAS,OAAO,WAAA,CAAA,EAAc;AAC3D,IAAA,MAAM,SAAS,MAAA,CAAO,IAAA;AAAA,MACpB,GAAG,MAAA,CAAO,QAAQ,IAAI,MAAA,CAAO,KAAA,IAAS,OAAO,WAAW,CAAA,CAAA;AAAA,MACxD;AAAA,KACF;AACA,IAAA,OAAA,CAAQ,aAAA,GAAgB,CAAA,MAAA,EAAS,MAAA,CAAO,QAAA,CAAS,QAAQ,CAAC,CAAA,CAAA;AAAA,EAC5D;AAEA,EAAA,OAAO,EAAE,OAAA,EAAQ;AACnB;;;;;;;"}
@@ -52,16 +52,14 @@ function getBitbucketCloudFileFetchUrl(url, config) {
52
52
  }
53
53
  function getBitbucketCloudRequestOptions(config) {
54
54
  const headers = {};
55
- if (config.username && config.appPassword) {
55
+ if (config.username && (config.token ?? config.appPassword)) {
56
56
  const buffer = Buffer.from(
57
- `${config.username}:${config.appPassword}`,
57
+ `${config.username}:${config.token ?? config.appPassword}`,
58
58
  "utf8"
59
59
  );
60
60
  headers.Authorization = `Basic ${buffer.toString("base64")}`;
61
61
  }
62
- return {
63
- headers
64
- };
62
+ return { headers };
65
63
  }
66
64
 
67
65
  export { getBitbucketCloudDefaultBranch, getBitbucketCloudDownloadUrl, getBitbucketCloudFileFetchUrl, getBitbucketCloudRequestOptions };
@@ -1 +1 @@
1
- {"version":3,"file":"core.esm.js","sources":["../../src/bitbucketCloud/core.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport fetch from 'cross-fetch';\nimport parseGitUrl from 'git-url-parse';\nimport { BitbucketCloudIntegrationConfig } from './config';\n\n/**\n * Given a URL pointing to a path on a provider, returns the default branch.\n *\n * @param url - A URL pointing to a path\n * @param config - The relevant provider config\n * @public\n */\nexport async function getBitbucketCloudDefaultBranch(\n url: string,\n config: BitbucketCloudIntegrationConfig,\n): Promise<string> {\n const { name: repoName, owner: project } = parseGitUrl(url);\n\n const branchUrl = `${config.apiBaseUrl}/repositories/${project}/${repoName}`;\n const response = await fetch(\n branchUrl,\n getBitbucketCloudRequestOptions(config),\n );\n\n if (!response.ok) {\n const message = `Failed to retrieve default branch from ${branchUrl}, ${response.status} ${response.statusText}`;\n throw new Error(message);\n }\n\n const repoInfo = await response.json();\n const defaultBranch = repoInfo.mainbranch.name;\n if (!defaultBranch) {\n throw new Error(\n `Failed to read default branch from ${branchUrl}. ` +\n `Response ${response.status} ${response.json()}`,\n );\n }\n return defaultBranch;\n}\n\n/**\n * Given a URL pointing to a path on a provider, returns a URL that is suitable\n * for downloading the subtree.\n *\n * @param url - A URL pointing to a path\n * @param config - The relevant provider config\n * @public\n */\nexport async function getBitbucketCloudDownloadUrl(\n url: string,\n config: BitbucketCloudIntegrationConfig,\n): Promise<string> {\n const {\n name: repoName,\n owner: project,\n ref,\n protocol,\n resource,\n } = parseGitUrl(url);\n\n let branch = ref;\n if (!branch) {\n branch = await getBitbucketCloudDefaultBranch(url, config);\n }\n return `${protocol}://${resource}/${project}/${repoName}/get/${branch}.tar.gz`;\n}\n\n/**\n * Given a URL pointing to a file on a provider, returns a URL that is suitable\n * for fetching the contents of the data.\n *\n * @remarks\n *\n * Converts\n * from: https://bitbucket.org/orgname/reponame/src/master/file.yaml\n * to: https://api.bitbucket.org/2.0/repositories/orgname/reponame/src/master/file.yaml\n *\n * @param url - A URL pointing to a file\n * @param config - The relevant provider config\n * @public\n */\nexport function getBitbucketCloudFileFetchUrl(\n url: string,\n config: BitbucketCloudIntegrationConfig,\n): string {\n try {\n const { owner, name, ref, filepathtype, filepath } = parseGitUrl(url);\n if (!owner || !name || (filepathtype !== 'src' && filepathtype !== 'raw')) {\n throw new Error('Invalid Bitbucket Cloud URL or file path');\n }\n\n const pathWithoutSlash = filepath.replace(/^\\//, '');\n\n if (!ref) {\n throw new Error('Invalid Bitbucket Cloud URL or file path');\n }\n return `${config.apiBaseUrl}/repositories/${owner}/${name}/src/${ref}/${pathWithoutSlash}`;\n } catch (e) {\n throw new Error(`Incorrect URL: ${url}, ${e}`);\n }\n}\n\n/**\n * Gets the request options necessary to make requests to a given provider.\n *\n * @param config - The relevant provider config\n * @public\n */\nexport function getBitbucketCloudRequestOptions(\n config: BitbucketCloudIntegrationConfig,\n): { headers: Record<string, string> } {\n const headers: Record<string, string> = {};\n\n if (config.username && config.appPassword) {\n const buffer = Buffer.from(\n `${config.username}:${config.appPassword}`,\n 'utf8',\n );\n headers.Authorization = `Basic ${buffer.toString('base64')}`;\n }\n\n return {\n headers,\n };\n}\n"],"names":[],"mappings":";;;AA2BA,eAAsB,8BAAA,CACpB,KACA,MAAA,EACiB;AACjB,EAAA,MAAM,EAAE,IAAA,EAAM,QAAA,EAAU,OAAO,OAAA,EAAQ,GAAI,YAAY,GAAG,CAAA;AAE1D,EAAA,MAAM,YAAY,CAAA,EAAG,MAAA,CAAO,UAAU,CAAA,cAAA,EAAiB,OAAO,IAAI,QAAQ,CAAA,CAAA;AAC1E,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stage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport fetch from 'cross-fetch';\nimport parseGitUrl from 'git-url-parse';\nimport { BitbucketCloudIntegrationConfig } from './config';\n\n/**\n * Given a URL pointing to a path on a provider, returns the default branch.\n *\n * @param url - A URL pointing to a path\n * @param config - The relevant provider config\n * @public\n */\nexport async function getBitbucketCloudDefaultBranch(\n url: string,\n config: BitbucketCloudIntegrationConfig,\n): Promise<string> {\n const { name: repoName, owner: project } = parseGitUrl(url);\n\n const branchUrl = `${config.apiBaseUrl}/repositories/${project}/${repoName}`;\n const response = await fetch(\n branchUrl,\n getBitbucketCloudRequestOptions(config),\n );\n\n if (!response.ok) {\n const message = `Failed to retrieve default branch from ${branchUrl}, ${response.status} ${response.statusText}`;\n throw new Error(message);\n }\n\n const repoInfo = await response.json();\n const defaultBranch = repoInfo.mainbranch.name;\n if (!defaultBranch) {\n throw new Error(\n `Failed to read default branch from ${branchUrl}. ` +\n `Response ${response.status} ${response.json()}`,\n );\n }\n return defaultBranch;\n}\n\n/**\n * Given a URL pointing to a path on a provider, returns a URL that is suitable\n * for downloading the subtree.\n *\n * @param url - A URL pointing to a path\n * @param config - The relevant provider config\n * @public\n */\nexport async function getBitbucketCloudDownloadUrl(\n url: string,\n config: BitbucketCloudIntegrationConfig,\n): Promise<string> {\n const {\n name: repoName,\n owner: project,\n ref,\n protocol,\n resource,\n } = parseGitUrl(url);\n\n let branch = ref;\n if (!branch) {\n branch = await getBitbucketCloudDefaultBranch(url, config);\n }\n return `${protocol}://${resource}/${project}/${repoName}/get/${branch}.tar.gz`;\n}\n\n/**\n * Given a URL pointing to a file on a provider, returns a URL that is suitable\n * for fetching the contents of the data.\n *\n * @remarks\n *\n * Converts\n * from: https://bitbucket.org/orgname/reponame/src/master/file.yaml\n * to: https://api.bitbucket.org/2.0/repositories/orgname/reponame/src/master/file.yaml\n *\n * @param url - A URL pointing to a file\n * @param config - The relevant provider config\n * @public\n */\nexport function getBitbucketCloudFileFetchUrl(\n url: string,\n config: BitbucketCloudIntegrationConfig,\n): string {\n try {\n const { owner, name, ref, filepathtype, filepath } = parseGitUrl(url);\n if (!owner || !name || (filepathtype !== 'src' && filepathtype !== 'raw')) {\n throw new Error('Invalid Bitbucket Cloud URL or file path');\n }\n\n const pathWithoutSlash = filepath.replace(/^\\//, '');\n\n if (!ref) {\n throw new Error('Invalid Bitbucket Cloud URL or file path');\n }\n return `${config.apiBaseUrl}/repositories/${owner}/${name}/src/${ref}/${pathWithoutSlash}`;\n } catch (e) {\n throw new Error(`Incorrect URL: ${url}, ${e}`);\n }\n}\n\n/**\n * Gets the request options necessary to make requests to a given provider.\n * Returns headers for authenticating with Bitbucket Cloud.\n * Supports both username/token and username/appPassword auth.\n *\n * @param config - The relevant provider config\n * @public\n */\nexport function getBitbucketCloudRequestOptions(\n config: BitbucketCloudIntegrationConfig,\n): {\n headers: Record<string, string>;\n} {\n const headers: Record<string, string> = {};\n\n // TODO: appPassword can be removed once fully\n // deprecated by BitBucket on 9th June 2026.\n if (config.username && (config.token ?? config.appPassword)) {\n const buffer = Buffer.from(\n `${config.username}:${config.token ?? config.appPassword}`,\n 'utf8',\n );\n headers.Authorization = `Basic ${buffer.toString('base64')}`;\n }\n\n return { headers };\n}\n"],"names":[],"mappings":";;;AA2BA,eAAsB,8BAAA,CACpB,KACA,MAAA,EACiB;AACjB,EAAA,MAAM,EAAE,IAAA,EAAM,QAAA,EAAU,OAAO,OAAA,EAAQ,GAAI,YAAY,GAAG,CAAA;AAE1D,EAAA,MAAM,YAAY,CAAA,EAAG,MAAA,CAAO,UAAU,CAAA,cAAA,EAAiB,OA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 class GithubAppCredentialsMux {
162
162
  }
163
163
  }
164
164
  class SingleInstanceGithubCredentialsProvider {
165
- constructor(githubAppCredentialsMux, token) {
166
- this.githubAppCredentialsMux = githubAppCredentialsMux;
167
- this.token = token;
168
- }
169
165
  static create = (config) => {
170
166
  return new SingleInstanceGithubCredentialsProvider(
171
167
  new GithubAppCredentialsMux(config),
172
168
  config.token
173
169
  );
174
170
  };
171
+ githubAppCredentialsMux;
172
+ token;
173
+ constructor(githubAppCredentialsMux, token) {
174
+ this.githubAppCredentialsMux = githubAppCredentialsMux;
175
+ this.token = token;
176
+ }
175
177
  /**
176
178
  * Returns {@link GithubCredentials} for a given URL.
177
179
  *
@@ -1 +1 @@
1
- {"version":3,"file":"SingleInstanceGithubCredentialsProvider.cjs.js","sources":["../../src/github/SingleInstanceGithubCredentialsProvider.ts"],"sourcesContent":["/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport parseGitUrl from 'git-url-parse';\nimport { GithubAppConfig, GithubIntegrationConfig } from './config';\nimport { createAppAuth } from '@octokit/auth-app';\nimport { Octokit, RestEndpointMethodTypes } from '@octokit/rest';\nimport { DateTime } from 'luxon';\nimport {\n GithubCredentials,\n GithubCredentialsProvider,\n GithubCredentialType,\n} from './types';\n\ntype InstallationData = {\n installationId: number;\n suspended: boolean;\n};\n\ntype InstallationTokenData = {\n token: string;\n expiresAt: DateTime;\n repositories?: String[];\n};\n\nclass Cache {\n private readonly tokenCache = new Map<string, InstallationTokenData>();\n\n async getOrCreateToken(\n owner: string,\n repo: string | undefined,\n supplier: () => Promise<InstallationTokenData>,\n ): Promise<{ accessToken: string }> {\n let existingInstallationData = this.tokenCache.get(owner);\n\n if (\n !existingInstallationData ||\n this.isExpired(existingInstallationData.expiresAt)\n ) {\n existingInstallationData = await supplier();\n // Allow 10 minutes grace to account for clock skew\n existingInstallationData.expiresAt =\n existingInstallationData.expiresAt.minus({ minutes: 10 });\n this.tokenCache.set(owner, existingInstallationData);\n }\n\n if (!this.appliesToRepo(existingInstallationData, repo)) {\n throw new Error(\n `The Backstage GitHub application used in the ${owner} organization does not have access to a repository with the name ${repo}`,\n );\n }\n\n return { accessToken: existingInstallationData.token };\n }\n\n private isExpired = (date: DateTime) => DateTime.local() > date;\n\n private appliesToRepo(tokenData: InstallationTokenData, repo?: string) {\n // If no specific repo has been requested the token is applicable\n if (repo === undefined) {\n return true;\n }\n // If the token is restricted to repositories, the token only applies if the repo is in the allow list\n if (tokenData.repositories !== undefined) {\n return tokenData.repositories.includes(repo);\n }\n // Otherwise the token is applicable\n return true;\n }\n}\n\n/**\n * This accept header is required when calling App APIs in GitHub Enterprise.\n * It has no effect on calls to github.com and can probably be removed entirely\n * once GitHub Apps is out of preview.\n */\nconst HEADERS = {\n Accept: 'application/vnd.github.machine-man-preview+json',\n};\n\n/**\n * GithubAppManager issues and caches tokens for a specific GitHub App.\n */\nclass GithubAppManager {\n private readonly appClient: Octokit;\n private readonly baseUrl?: string;\n private readonly baseAuthConfig: { appId: number; privateKey: string };\n private readonly cache = new Cache();\n private readonly allowedInstallationOwners: string[] | undefined; // undefined allows all installations\n\n constructor(config: GithubAppConfig, baseUrl?: string) {\n this.allowedInstallationOwners = config.allowedInstallationOwners?.map(\n owner => owner.toLocaleLowerCase('en-US'),\n );\n this.baseUrl = baseUrl;\n this.baseAuthConfig = {\n appId: config.appId,\n privateKey: config.privateKey.replace(/\\\\n/gm, '\\n'),\n };\n this.appClient = new Octokit({\n baseUrl,\n headers: HEADERS,\n authStrategy: createAppAuth,\n auth: this.baseAuthConfig,\n });\n }\n\n async getInstallationCredentials(\n owner: string,\n repo?: string,\n ): Promise<{ accessToken: string | undefined }> {\n if (this.allowedInstallationOwners) {\n if (\n !this.allowedInstallationOwners?.includes(\n owner.toLocaleLowerCase('en-US'),\n )\n ) {\n return { accessToken: undefined }; // An empty token allows anonymous access to public repos\n }\n }\n\n // Go and grab an access token for the app scoped to a repository if provided, if not use the organisation installation.\n return this.cache.getOrCreateToken(owner, repo, async () => {\n const { installationId, suspended } = await this.getInstallationData(\n owner,\n );\n if (suspended) {\n throw new Error(`The GitHub application for ${owner} is suspended`);\n }\n\n const result = await this.appClient.apps.createInstallationAccessToken({\n installation_id: installationId,\n headers: HEADERS,\n });\n\n let repositoryNames;\n\n if (result.data.repository_selection === 'selected') {\n const installationClient = new Octokit({\n baseUrl: this.baseUrl,\n auth: result.data.token,\n });\n const repos = await installationClient.paginate(\n installationClient.apps.listReposAccessibleToInstallation,\n );\n // The return type of the paginate method is incorrect.\n const repositories: RestEndpointMethodTypes['apps']['listReposAccessibleToInstallation']['response']['data']['repositories'] =\n repos.repositories ?? repos;\n\n repositoryNames = repositories.map(repository => repository.name);\n }\n return {\n token: result.data.token,\n expiresAt: DateTime.fromISO(result.data.expires_at),\n repositories: repositoryNames,\n };\n });\n }\n\n getInstallations(): Promise<\n RestEndpointMethodTypes['apps']['listInstallations']['response']['data']\n > {\n return this.appClient.paginate(this.appClient.apps.listInstallations);\n }\n\n private async getInstallationData(owner: string): Promise<InstallationData> {\n const allInstallations = await this.getInstallations();\n const installation = allInstallations.find(\n inst =>\n inst.account &&\n 'login' in inst.account &&\n inst.account.login?.toLocaleLowerCase('en-US') ===\n owner.toLocaleLowerCase('en-US'),\n );\n if (installation) {\n return {\n installationId: installation.id,\n suspended: Boolean(installation.suspended_by),\n };\n }\n const notFoundError = new Error(\n `No app installation found for ${owner} in ${this.baseAuthConfig.appId}`,\n );\n notFoundError.name = 'NotFoundError';\n throw notFoundError;\n }\n}\n\n/**\n * Corresponds to a Github installation which internally could hold several GitHub Apps.\n *\n * @public\n */\nexport class GithubAppCredentialsMux {\n private readonly apps: GithubAppManager[];\n\n constructor(config: GithubIntegrationConfig, appIds: number[] = []) {\n this.apps =\n config.apps\n ?.filter(app => (appIds.length ? appIds.includes(app.appId) : true))\n .map(ac => new GithubAppManager(ac, config.apiBaseUrl)) ?? [];\n }\n\n async getAllInstallations(): Promise<\n RestEndpointMethodTypes['apps']['listInstallations']['response']['data']\n > {\n if (!this.apps.length) {\n return [];\n }\n\n const installs = await Promise.all(\n this.apps.map(app => app.getInstallations()),\n );\n\n return installs.flat();\n }\n\n async getAppToken(owner: string, repo?: string): Promise<string | undefined> {\n if (this.apps.length === 0) {\n return undefined;\n }\n\n const results = await Promise.all(\n this.apps.map(app =>\n app.getInstallationCredentials(owner, repo).then(\n credentials => ({ credentials, error: undefined }),\n error => ({ credentials: undefined, error }),\n ),\n ),\n );\n\n const result = results.find(\n resultItem => resultItem.credentials?.accessToken,\n );\n if (result) {\n return result.credentials!.accessToken;\n }\n\n const errors = results.map(r => r.error);\n const notNotFoundError = errors.find(err => err?.name !== 'NotFoundError');\n if (notNotFoundError) {\n throw notNotFoundError;\n }\n\n return undefined;\n }\n}\n\n/**\n * Handles the creation and caching of credentials for GitHub integrations.\n *\n * @public\n * @remarks\n *\n * TODO: Possibly move this to a backend only package so that it's not used in the frontend by mistake\n */\nexport class SingleInstanceGithubCredentialsProvider\n implements GithubCredentialsProvider\n{\n static create: (\n config: GithubIntegrationConfig,\n ) => GithubCredentialsProvider = config => {\n return new SingleInstanceGithubCredentialsProvider(\n new GithubAppCredentialsMux(config),\n config.token,\n );\n };\n\n private constructor(\n private readonly githubAppCredentialsMux: GithubAppCredentialsMux,\n private readonly token?: string,\n ) {}\n\n /**\n * Returns {@link GithubCredentials} for a given URL.\n *\n * @remarks\n *\n * Consecutive calls to this method with the same URL will return cached\n * credentials.\n *\n * The shortest lifetime for a token returned is 10 minutes.\n *\n * @example\n * ```ts\n * const { token, headers } = await getCredentials({\n * url: 'github.com/backstage/foobar'\n * })\n * ```\n *\n * @param opts - The organization or repository URL\n * @returns A promise of {@link GithubCredentials}.\n */\n async getCredentials(opts: { url: string }): Promise<GithubCredentials> {\n const parsed = parseGitUrl(opts.url);\n\n const owner = parsed.owner || parsed.name;\n const repo = parsed.owner ? parsed.name : undefined;\n\n let type: GithubCredentialType = 'app';\n let token = await this.githubAppCredentialsMux.getAppToken(owner, repo);\n if (!token) {\n type = 'token';\n token = this.token;\n }\n\n return {\n headers: token ? { Authorization: `Bearer ${token}` } : undefined,\n token,\n type,\n };\n }\n}\n"],"names":["DateTime","Octokit","createAppAuth","parseGitUrl"],"mappings":";;;;;;;;;;;AAsCA,MAAM,KAAA,CAAM;AAAA,EACO,UAAA,uBAAiB,GAAA,EAAmC;AAAA,EAErE,MAAM,gBAAA,CACJ,KAAA,EACA,IAAA,EACA,QAAA,EACkC;AAClC,IAAA,IAAI,wBAAA,GAA2B,IAAA,CAAK,UAAA,CAAW,GAAA,CAAI,KAAK,CAAA;AAExD,IAAA,IACE,CAAC,wBAAA,IACD,IAAA,CAAK,SAAA,CAAU,wBAAA,CAAyB,SAAS,CAAA,EACjD;AACA,MAAA,wBAAA,GAA2B,MAAM,QAAA,EAAS;AAE1C,MAAA,wBAAA,CAAyB,YACvB,wBAAA,CAAyB,SAAA,CAAU,MAAM,EAAE,OAAA,EAAS,IAAI,CAAA;AAC1D,MAAA,IAAA,CAAK,UAAA,CAAW,GAAA,CAAI,KAAA,EAAO,wBAAwB,CAAA;AAAA,IACrD;AAEA,IAAA,IAAI,CAAC,IAAA,CAAK,aAAA,CAAc,wBAAA,EAA0B,IAAI,CAAA,EAAG;AACvD,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,CAAA,6CAAA,EAAgD,KAAK,CAAA,iEAAA,EAAoE,IAAI,CAAA;AAAA,OAC/H;AAAA,IACF;AAEA,IAAA,OAAO,EAAE,WAAA,EAAa,wBAAA,CAAyB,KAAA,EAAM;AAAA,EACvD;AAAA,EAEQ,SAAA,GAAY,CAAC,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K,IAAG,GAAI,MAAA;AAAA,MACxD,KAAA;AAAA,MACA;AAAA,KACF;AAAA,EACF;AACF;;;;;"}
1
+ {"version":3,"file":"SingleInstanceGithubCredentialsProvider.cjs.js","sources":["../../src/github/SingleInstanceGithubCredentialsProvider.ts"],"sourcesContent":["/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport parseGitUrl from 'git-url-parse';\nimport { GithubAppConfig, GithubIntegrationConfig } from './config';\nimport { createAppAuth } from '@octokit/auth-app';\nimport { Octokit, RestEndpointMethodTypes } from '@octokit/rest';\nimport { DateTime } from 'luxon';\nimport {\n GithubCredentials,\n GithubCredentialsProvider,\n GithubCredentialType,\n} from './types';\n\ntype InstallationData = {\n installationId: number;\n suspended: boolean;\n};\n\ntype InstallationTokenData = {\n token: string;\n expiresAt: DateTime;\n repositories?: String[];\n};\n\nclass Cache {\n private readonly tokenCache = new Map<string, InstallationTokenData>();\n\n async getOrCreateToken(\n owner: string,\n repo: string | undefined,\n supplier: () => Promise<InstallationTokenData>,\n ): Promise<{ accessToken: string }> {\n let existingInstallationData = this.tokenCache.get(owner);\n\n if (\n !existingInstallationData ||\n this.isExpired(existingInstallationData.expiresAt)\n ) {\n existingInstallationData = await supplier();\n // Allow 10 minutes grace to account for clock skew\n existingInstallationData.expiresAt =\n existingInstallationData.expiresAt.minus({ minutes: 10 });\n this.tokenCache.set(owner, existingInstallationData);\n }\n\n if (!this.appliesToRepo(existingInstallationData, repo)) {\n throw new Error(\n `The Backstage GitHub application used in the ${owner} organization does not have access to a repository with the name ${repo}`,\n );\n }\n\n return { accessToken: existingInstallationData.token };\n }\n\n private isExpired = (date: DateTime) => DateTime.local() > date;\n\n private appliesToRepo(tokenData: InstallationTokenData, repo?: string) {\n // If no specific repo has been requested the token is applicable\n if (repo === undefined) {\n return true;\n }\n // If the token is restricted to repositories, the token only applies if the repo is in the allow list\n if (tokenData.repositories !== undefined) {\n return tokenData.repositories.includes(repo);\n }\n // Otherwise the token is applicable\n return true;\n }\n}\n\n/**\n * This accept header is required when calling App APIs in GitHub Enterprise.\n * It has no effect on calls to github.com and can probably be removed entirely\n * once GitHub Apps is out of preview.\n */\nconst HEADERS = {\n Accept: 'application/vnd.github.machine-man-preview+json',\n};\n\n/**\n * GithubAppManager issues and caches tokens for a specific GitHub App.\n */\nclass GithubAppManager {\n private readonly appClient: Octokit;\n private readonly baseUrl?: string;\n private readonly baseAuthConfig: { appId: number; privateKey: string };\n private readonly cache = new Cache();\n private readonly allowedInstallationOwners: string[] | undefined; // undefined allows all installations\n\n constructor(config: GithubAppConfig, baseUrl?: string) {\n this.allowedInstallationOwners = config.allowedInstallationOwners?.map(\n owner => owner.toLocaleLowerCase('en-US'),\n );\n this.baseUrl = baseUrl;\n this.baseAuthConfig = {\n appId: config.appId,\n privateKey: config.privateKey.replace(/\\\\n/gm, '\\n'),\n };\n this.appClient = new Octokit({\n baseUrl,\n headers: HEADERS,\n authStrategy: createAppAuth,\n auth: this.baseAuthConfig,\n });\n }\n\n async getInstallationCredentials(\n owner: string,\n repo?: string,\n ): Promise<{ accessToken: string | undefined }> {\n if (this.allowedInstallationOwners) {\n if (\n !this.allowedInstallationOwners?.includes(\n owner.toLocaleLowerCase('en-US'),\n )\n ) {\n return { accessToken: undefined }; // An empty token allows anonymous access to public repos\n }\n }\n\n // Go and grab an access token for the app scoped to a repository if provided, if not use the organisation installation.\n return this.cache.getOrCreateToken(owner, repo, async () => {\n const { installationId, suspended } = await this.getInstallationData(\n owner,\n );\n if (suspended) {\n throw new Error(`The GitHub application for ${owner} is suspended`);\n }\n\n const result = await this.appClient.apps.createInstallationAccessToken({\n installation_id: installationId,\n headers: HEADERS,\n });\n\n let repositoryNames;\n\n if (result.data.repository_selection === 'selected') {\n const installationClient = new Octokit({\n baseUrl: this.baseUrl,\n auth: result.data.token,\n });\n const repos = await installationClient.paginate(\n installationClient.apps.listReposAccessibleToInstallation,\n );\n // The return type of the paginate method is incorrect.\n const repositories: RestEndpointMethodTypes['apps']['listReposAccessibleToInstallation']['response']['data']['repositories'] =\n repos.repositories ?? repos;\n\n repositoryNames = repositories.map(repository => repository.name);\n }\n return {\n token: result.data.token,\n expiresAt: DateTime.fromISO(result.data.expires_at),\n repositories: repositoryNames,\n };\n });\n }\n\n getInstallations(): Promise<\n RestEndpointMethodTypes['apps']['listInstallations']['response']['data']\n > {\n return this.appClient.paginate(this.appClient.apps.listInstallations);\n }\n\n private async getInstallationData(owner: string): Promise<InstallationData> {\n const allInstallations = await this.getInstallations();\n const installation = allInstallations.find(\n inst =>\n inst.account &&\n 'login' in inst.account &&\n inst.account.login?.toLocaleLowerCase('en-US') ===\n owner.toLocaleLowerCase('en-US'),\n );\n if (installation) {\n return {\n installationId: installation.id,\n suspended: Boolean(installation.suspended_by),\n };\n }\n const notFoundError = new Error(\n `No app installation found for ${owner} in ${this.baseAuthConfig.appId}`,\n );\n notFoundError.name = 'NotFoundError';\n throw notFoundError;\n }\n}\n\n/**\n * Corresponds to a Github installation which internally could hold several GitHub Apps.\n *\n * @public\n */\nexport class GithubAppCredentialsMux {\n private readonly apps: GithubAppManager[];\n\n constructor(config: GithubIntegrationConfig, appIds: number[] = []) {\n this.apps =\n config.apps\n ?.filter(app => (appIds.length ? appIds.includes(app.appId) : true))\n .map(ac => new GithubAppManager(ac, config.apiBaseUrl)) ?? [];\n }\n\n async getAllInstallations(): Promise<\n RestEndpointMethodTypes['apps']['listInstallations']['response']['data']\n > {\n if (!this.apps.length) {\n return [];\n }\n\n const installs = await Promise.all(\n this.apps.map(app => app.getInstallations()),\n );\n\n return installs.flat();\n }\n\n async getAppToken(owner: string, repo?: string): Promise<string | undefined> {\n if (this.apps.length === 0) {\n return undefined;\n }\n\n const results = await Promise.all(\n this.apps.map(app =>\n app.getInstallationCredentials(owner, repo).then(\n credentials => ({ credentials, error: undefined }),\n error => ({ credentials: undefined, error }),\n ),\n ),\n );\n\n const result = results.find(\n resultItem => resultItem.credentials?.accessToken,\n );\n if (result) {\n return result.credentials!.accessToken;\n }\n\n const errors = results.map(r => r.error);\n const notNotFoundError = errors.find(err => err?.name !== 'NotFoundError');\n if (notNotFoundError) {\n throw notNotFoundError;\n }\n\n return undefined;\n }\n}\n\n/**\n * Handles the creation and caching of credentials for GitHub integrations.\n *\n * @public\n * @remarks\n *\n * TODO: Possibly move this to a backend only package so that it's not used in the frontend by mistake\n */\nexport class SingleInstanceGithubCredentialsProvider\n implements GithubCredentialsProvider\n{\n static create: (\n config: GithubIntegrationConfig,\n ) => GithubCredentialsProvider = config => {\n return new SingleInstanceGithubCredentialsProvider(\n new GithubAppCredentialsMux(config),\n config.token,\n );\n };\n\n private readonly githubAppCredentialsMux: GithubAppCredentialsMux;\n private readonly token?: string;\n\n private constructor(\n githubAppCredentialsMux: GithubAppCredentialsMux,\n token?: string,\n ) {\n this.githubAppCredentialsMux = githubAppCredentialsMux;\n this.token = token;\n }\n\n /**\n * Returns {@link GithubCredentials} for a given URL.\n *\n * @remarks\n *\n * Consecutive calls to this method with the same URL will return cached\n * credentials.\n *\n * The shortest lifetime for a token returned is 10 minutes.\n *\n * @example\n * ```ts\n * const { token, headers } = await getCredentials({\n * url: 'github.com/backstage/foobar'\n * })\n * ```\n *\n * @param opts - The organization or repository URL\n * @returns A promise of {@link GithubCredentials}.\n */\n async getCredentials(opts: { url: string }): Promise<GithubCredentials> {\n const parsed = parseGitUrl(opts.url);\n\n const owner = parsed.owner || parsed.name;\n const repo = parsed.owner ? parsed.name : undefined;\n\n let type: GithubCredentialType = 'app';\n let token = await this.githubAppCredentialsMux.getAppToken(owner, repo);\n if (!token) {\n type = 'token';\n token = this.token;\n }\n\n return {\n headers: token ? { Authorization: `Bearer ${token}` } : undefined,\n token,\n type,\n };\n }\n}\n"],"names":["DateTime","Octokit","createAppAuth","parseGitUrl"],"mappings":";;;;;;;;;;;AAsCA,MAAM,KAAA,CAAM;AAAA,EACO,UAAA,uBAAiB,GAAA,EAAmC;AAAA,EAErE,MAAM,gBAAA,CACJ,KAAA,EACA,IAAA,EACA,QAAA,EACkC;AAClC,IAAA,IAAI,wBAAA,GAA2B,IAAA,CAAK,UAAA,CAAW,GAAA,CAAI,KAAK,CAAA;AAExD,IAAA,IACE,CAAC,wBAAA,IACD,IAAA,CAAK,SAAA,CAAU,wBAAA,CAAyB,SAAS,CAAA,EACjD;AACA,MAAA,wBAAA,GAA2B,MAAM,QAAA,EAAS;AAE1C,MAAA,wBAAA,CAAyB,YACvB,wBAAA,CAAyB,SAAA,CAAU,MAAM,EAAE,OAAA,EAAS,IAAI,CAAA;AAC1D,MAAA,IAAA,CAAK,UAAA,CAAW,GAAA,CAAI,KAAA,EAAO,wBAAwB,CAAA;AAAA,IACrD;AAEA,IAAA,IAAI,CAAC,IAAA,CAAK,aAAA,CAAc,wBAAA,EAA0B,IAAI,CAAA,EAAG;AACvD,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,CAAA,6CAAA,EAAgD,KAAK,CAAA,iEAAA,EAAoE,IAAI,CAAA;AAAA,OAC/H;AAAA,IACF;AAEA,IAAA,OAAO,EAAE,WAAA,EAAa,wBAAA,CAAyB,KAAA,EAAM;AAAA,EACvD;AAAA,EAEQ,SAAA,GAAY,CAAC,IAAA,KAAmBA,cAAA,CAAS,OAAM,GAAI,IAAA;AAAA,EAEnD,aAAA,CAAc,WAAkC,IAAA,EAAe;AAErE,IAAA,IAAI,SAAS,MAAA,EAAW;AACtB,MAAA,OAAO,IAAA;AAAA,IACT;AAEA,IAAA,IAAI,SAAA,CAAU,iBAAiB,MAAA,EAAW;AACxC,MAAA,OAAO,SAAA,CAAU,YAAA,CAAa,QAAA,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AACzC,IAAA,OAAO,IAAI,uCAAA;AAAA,MACT,IAAI,wBAAwB,MAAM,CAAA;AAAA,MAClC,MAAA,CAAO;AAAA,KACT;AAAA,EACF,CAAA;AAAA,EAEiB,uBAAA;AAAA,EACA,KAAA;AAAA,EAET,WAAA,CACN,yBACA,KAAA,EACA;AACA,IAAA,IAAA,CAAK,uBAAA,GAA0B,uBAAA;AAC/B,IAAA,IAAA,CAAK,KAAA,GAAQ,KAAA;AAAA,EACf;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAsBA,MAAM,eAAe,IAAA,EAAmD;AACtE,IAAA,MAAM,MAAA,GAASG,4BAAA,CAAY,IAAA,CAAK,GAAG,CAAA;AAEnC,IAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,KAAA,IAAS,MAAA,CAAO,IAAA;AACrC,IAAA,MAAM,IAAA,GAAO,MAAA,CAAO,KAAA,GAAQ,MAAA,CAAO,IAAA,GAAO,MAAA;AAE1C,IAAA,IAAI,IAAA,GAA6B,KAAA;AACjC,IAAA,IAAI,QAAQ,MAAM,IAAA,CAAK,uBAAA,CAAwB,WAAA,CAAY,OAAO,IAAI,CAAA;AACtE,IAAA,IAAI,CAAC,KAAA,EAAO;AACV,MAAA,IAAA,GAAO,OAAA;AACP,MAAA,KAAA,GAAQ,IAAA,CAAK,KAAA;AAAA,IACf;AAEA,IAAA,OAAO;AAAA,MACL,SAAS,KAAA,GAAQ,EAAE,eAAe,CAAA,OAAA,EAAU,KAAK,IAAG,GAAI,MAAA;AAAA,MACxD,KAAA;AAAA,MACA;AAAA,KACF;AAAA,EACF;AACF;;;;;"}
@@ -156,16 +156,18 @@ class GithubAppCredentialsMux {
156
156
  }
157
157
  }
158
158
  class SingleInstanceGithubCredentialsProvider {
159
- constructor(githubAppCredentialsMux, token) {
160
- this.githubAppCredentialsMux = githubAppCredentialsMux;
161
- this.token = token;
162
- }
163
159
  static create = (config) => {
164
160
  return new SingleInstanceGithubCredentialsProvider(
165
161
  new GithubAppCredentialsMux(config),
166
162
  config.token
167
163
  );
168
164
  };
165
+ githubAppCredentialsMux;
166
+ token;
167
+ constructor(githubAppCredentialsMux, token) {
168
+ this.githubAppCredentialsMux = githubAppCredentialsMux;
169
+ this.token = token;
170
+ }
169
171
  /**
170
172
  * Returns {@link GithubCredentials} for a given URL.
171
173
  *
@@ -1 +1 @@
1
- {"version":3,"file":"SingleInstanceGithubCredentialsProvider.esm.js","sources":["../../src/github/SingleInstanceGithubCredentialsProvider.ts"],"sourcesContent":["/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport parseGitUrl from 'git-url-parse';\nimport { GithubAppConfig, GithubIntegrationConfig } from './config';\nimport { createAppAuth } from '@octokit/auth-app';\nimport { Octokit, RestEndpointMethodTypes } from '@octokit/rest';\nimport { DateTime } from 'luxon';\nimport {\n GithubCredentials,\n GithubCredentialsProvider,\n GithubCredentialType,\n} from './types';\n\ntype InstallationData = {\n installationId: number;\n suspended: boolean;\n};\n\ntype InstallationTokenData = {\n token: string;\n expiresAt: DateTime;\n repositories?: String[];\n};\n\nclass Cache {\n private readonly tokenCache = new Map<string, InstallationTokenData>();\n\n async getOrCreateToken(\n owner: string,\n repo: string | undefined,\n supplier: () => Promise<InstallationTokenData>,\n ): Promise<{ accessToken: string }> {\n let existingInstallationData = this.tokenCache.get(owner);\n\n if (\n !existingInstallationData ||\n this.isExpired(existingInstallationData.expiresAt)\n ) {\n existingInstallationData = await supplier();\n // Allow 10 minutes grace to account for clock skew\n existingInstallationData.expiresAt =\n existingInstallationData.expiresAt.minus({ minutes: 10 });\n this.tokenCache.set(owner, existingInstallationData);\n }\n\n if (!this.appliesToRepo(existingInstallationData, repo)) {\n throw new Error(\n `The Backstage GitHub application used in the ${owner} organization does not have access to a repository with the name ${repo}`,\n );\n }\n\n return { accessToken: existingInstallationData.token };\n }\n\n private isExpired = (date: DateTime) => DateTime.local() > date;\n\n private appliesToRepo(tokenData: InstallationTokenData, repo?: string) {\n // If no specific repo has been requested the token is applicable\n if (repo === undefined) {\n return true;\n }\n // If the token is restricted to repositories, the token only applies if the repo is in the allow list\n if (tokenData.repositories !== undefined) {\n return tokenData.repositories.includes(repo);\n }\n // Otherwise the token is applicable\n return true;\n }\n}\n\n/**\n * This accept header is required when calling App APIs in GitHub Enterprise.\n * It has no effect on calls to github.com and can probably be removed entirely\n * once GitHub Apps is out of preview.\n */\nconst HEADERS = {\n Accept: 'application/vnd.github.machine-man-preview+json',\n};\n\n/**\n * GithubAppManager issues and caches tokens for a specific GitHub App.\n */\nclass GithubAppManager {\n private readonly appClient: Octokit;\n private readonly baseUrl?: string;\n private readonly baseAuthConfig: { appId: number; privateKey: string };\n private readonly cache = new Cache();\n private readonly allowedInstallationOwners: string[] | undefined; // undefined allows all installations\n\n constructor(config: GithubAppConfig, baseUrl?: string) {\n this.allowedInstallationOwners = config.allowedInstallationOwners?.map(\n owner => owner.toLocaleLowerCase('en-US'),\n );\n this.baseUrl = baseUrl;\n this.baseAuthConfig = {\n appId: config.appId,\n privateKey: config.privateKey.replace(/\\\\n/gm, '\\n'),\n };\n this.appClient = new Octokit({\n baseUrl,\n headers: HEADERS,\n authStrategy: createAppAuth,\n auth: this.baseAuthConfig,\n });\n }\n\n async getInstallationCredentials(\n owner: string,\n repo?: string,\n ): Promise<{ accessToken: string | undefined }> {\n if (this.allowedInstallationOwners) {\n if (\n !this.allowedInstallationOwners?.includes(\n owner.toLocaleLowerCase('en-US'),\n )\n ) {\n return { accessToken: undefined }; // An empty token allows anonymous access to public repos\n }\n }\n\n // Go and grab an access token for the app scoped to a repository if provided, if not use the organisation installation.\n return this.cache.getOrCreateToken(owner, repo, async () => {\n const { installationId, suspended } = await this.getInstallationData(\n owner,\n );\n if (suspended) {\n throw new Error(`The GitHub application for ${owner} is suspended`);\n }\n\n const result = await this.appClient.apps.createInstallationAccessToken({\n installation_id: installationId,\n headers: HEADERS,\n });\n\n let repositoryNames;\n\n if (result.data.repository_selection === 'selected') {\n const installationClient = new Octokit({\n baseUrl: this.baseUrl,\n auth: result.data.token,\n });\n const repos = await installationClient.paginate(\n installationClient.apps.listReposAccessibleToInstallation,\n );\n // The return type of the paginate method is incorrect.\n const repositories: RestEndpointMethodTypes['apps']['listReposAccessibleToInstallation']['response']['data']['repositories'] =\n repos.repositories ?? repos;\n\n repositoryNames = repositories.map(repository => repository.name);\n }\n return {\n token: result.data.token,\n expiresAt: DateTime.fromISO(result.data.expires_at),\n repositories: repositoryNames,\n };\n });\n }\n\n getInstallations(): Promise<\n RestEndpointMethodTypes['apps']['listInstallations']['response']['data']\n > {\n return this.appClient.paginate(this.appClient.apps.listInstallations);\n }\n\n private async getInstallationData(owner: string): Promise<InstallationData> {\n const allInstallations = await this.getInstallations();\n const installation = allInstallations.find(\n inst =>\n inst.account &&\n 'login' in inst.account &&\n inst.account.login?.toLocaleLowerCase('en-US') ===\n owner.toLocaleLowerCase('en-US'),\n );\n if (installation) {\n return {\n installationId: installation.id,\n suspended: Boolean(installation.suspended_by),\n };\n }\n const notFoundError = new Error(\n `No app installation found for ${owner} in ${this.baseAuthConfig.appId}`,\n );\n notFoundError.name = 'NotFoundError';\n throw notFoundError;\n }\n}\n\n/**\n * Corresponds to a Github installation which internally could hold several GitHub Apps.\n *\n * @public\n */\nexport class GithubAppCredentialsMux {\n private readonly apps: GithubAppManager[];\n\n constructor(config: GithubIntegrationConfig, appIds: number[] = []) {\n this.apps =\n config.apps\n ?.filter(app => (appIds.length ? appIds.includes(app.appId) : true))\n .map(ac => new GithubAppManager(ac, config.apiBaseUrl)) ?? [];\n }\n\n async getAllInstallations(): Promise<\n RestEndpointMethodTypes['apps']['listInstallations']['response']['data']\n > {\n if (!this.apps.length) {\n return [];\n }\n\n const installs = await Promise.all(\n this.apps.map(app => app.getInstallations()),\n );\n\n return installs.flat();\n }\n\n async getAppToken(owner: string, repo?: string): Promise<string | undefined> {\n if (this.apps.length === 0) {\n return undefined;\n }\n\n const results = await Promise.all(\n this.apps.map(app =>\n app.getInstallationCredentials(owner, repo).then(\n credentials => ({ credentials, error: undefined }),\n error => ({ credentials: undefined, error }),\n ),\n ),\n );\n\n const result = results.find(\n resultItem => resultItem.credentials?.accessToken,\n );\n if (result) {\n return result.credentials!.accessToken;\n }\n\n const errors = results.map(r => r.error);\n const notNotFoundError = errors.find(err => err?.name !== 'NotFoundError');\n if (notNotFoundError) {\n throw notNotFoundError;\n }\n\n return undefined;\n }\n}\n\n/**\n * Handles the creation and caching of credentials for GitHub integrations.\n *\n * @public\n * @remarks\n *\n * TODO: Possibly move this to a backend only package so that it's not used in the frontend by mistake\n */\nexport class SingleInstanceGithubCredentialsProvider\n implements GithubCredentialsProvider\n{\n static create: (\n config: GithubIntegrationConfig,\n ) => GithubCredentialsProvider = config => {\n return new SingleInstanceGithubCredentialsProvider(\n new GithubAppCredentialsMux(config),\n config.token,\n );\n };\n\n private constructor(\n private readonly githubAppCredentialsMux: GithubAppCredentialsMux,\n private readonly token?: string,\n ) {}\n\n /**\n * Returns {@link GithubCredentials} for a given URL.\n *\n * @remarks\n *\n * Consecutive calls to this method with the same URL will return cached\n * credentials.\n *\n * The shortest lifetime for a token returned is 10 minutes.\n *\n * @example\n * ```ts\n * const { token, headers } = await getCredentials({\n * url: 'github.com/backstage/foobar'\n * })\n * ```\n *\n * @param opts - The organization or repository URL\n * @returns A promise of {@link GithubCredentials}.\n */\n async getCredentials(opts: { url: string }): Promise<GithubCredentials> {\n const parsed = parseGitUrl(opts.url);\n\n const owner = parsed.owner || parsed.name;\n const repo = parsed.owner ? parsed.name : undefined;\n\n let type: GithubCredentialType = 'app';\n let token = await this.githubAppCredentialsMux.getAppToken(owner, repo);\n if (!token) {\n type = 'token';\n token = this.token;\n }\n\n return {\n headers: token ? { Authorization: `Bearer ${token}` } : undefined,\n token,\n type,\n };\n }\n}\n"],"names":[],"mappings":";;;;;AAsCA,MAAM,KAAA,CAAM;AAAA,EACO,UAAA,uBAAiB,GAAA,EAAmC;AAAA,EAErE,MAAM,gBAAA,CACJ,KAAA,EACA,IAAA,EACA,QAAA,EACkC;AAClC,IAAA,IAAI,wBAAA,GAA2B,IAAA,CAAK,UAAA,CAAW,GAAA,CAAI,KAAK,CAAA;AAExD,IAAA,IACE,CAAC,wBAAA,IACD,IAAA,CAAK,SAAA,CAAU,wBAAA,CAAyB,SAAS,CAAA,EACjD;AACA,MAAA,wBAAA,GAA2B,MAAM,QAAA,EAAS;AAE1C,MAAA,wBAAA,CAAyB,YACvB,wBAAA,CAAyB,SAAA,CAAU,MAAM,EAAE,OAAA,EAAS,IAAI,CAAA;AAC1D,MAAA,IAAA,CAAK,UAAA,CAAW,GAAA,CAAI,KAAA,EAAO,wBAAwB,CAAA;AAAA,IACrD;AAEA,IAAA,IAAI,CAAC,IAAA,CAAK,aAAA,CAAc,wBAAA,EAA0B,IAAI,CAAA,EAAG;AACvD,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,CAAA,6CAAA,EAAgD,KAAK,CAAA,iEAAA,EAAoE,IAAI,CAAA;AAAA,OAC/H;AAAA,IACF;AAEA,IAAA,OAAO,EAAE,WAAA,EAAa,wBAAA,CAAyB,KAAA,EAAM;AAAA,EACvD;AAAA,EAEQ,SAAA,GAAY,CAAC,IAAA,KAAmB,QAAA,CAAS,OAAM,GAAI,IAAA;AAAA,EAEnD,aAAA,CAAc,WAAkC,IAAA,EAAe;AAErE,IAAA,IAAI,SAAS,MAAA,EAAW;AACtB,MAAA,OAAO,IAAA;AAAA,IACT;A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],"sourcesContent":["/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport parseGitUrl from 'git-url-parse';\nimport { GithubAppConfig, GithubIntegrationConfig } from './config';\nimport { createAppAuth } from '@octokit/auth-app';\nimport { Octokit, RestEndpointMethodTypes } from '@octokit/rest';\nimport { DateTime } from 'luxon';\nimport {\n GithubCredentials,\n GithubCredentialsProvider,\n GithubCredentialType,\n} from './types';\n\ntype InstallationData = {\n installationId: number;\n suspended: boolean;\n};\n\ntype InstallationTokenData = {\n token: string;\n expiresAt: DateTime;\n repositories?: String[];\n};\n\nclass Cache {\n private readonly tokenCache = new Map<string, InstallationTokenData>();\n\n async getOrCreateToken(\n owner: string,\n repo: string | undefined,\n supplier: () => Promise<InstallationTokenData>,\n ): Promise<{ accessToken: string }> {\n let existingInstallationData = this.tokenCache.get(owner);\n\n if (\n !existingInstallationData ||\n this.isExpired(existingInstallationData.expiresAt)\n ) {\n existingInstallationData = await supplier();\n // Allow 10 minutes grace to account for clock skew\n existingInstallationData.expiresAt =\n existingInstallationData.expiresAt.minus({ minutes: 10 });\n this.tokenCache.set(owner, existingInstallationData);\n }\n\n if (!this.appliesToRepo(existingInstallationData, repo)) {\n throw new Error(\n `The Backstage GitHub application used in the ${owner} organization does not have access to a repository with the name ${repo}`,\n );\n }\n\n return { accessToken: existingInstallationData.token };\n }\n\n private isExpired = (date: DateTime) => DateTime.local() > date;\n\n private appliesToRepo(tokenData: InstallationTokenData, repo?: string) {\n // If no specific repo has been requested the token is applicable\n if (repo === undefined) {\n return true;\n }\n // If the token is restricted to repositories, the token only applies if the repo is in the allow list\n if (tokenData.repositories !== undefined) {\n return tokenData.repositories.includes(repo);\n }\n // Otherwise the token is applicable\n return true;\n }\n}\n\n/**\n * This accept header is required when calling App APIs in GitHub Enterprise.\n * It has no effect on calls to github.com and can probably be removed entirely\n * once GitHub Apps is out of preview.\n */\nconst HEADERS = {\n Accept: 'application/vnd.github.machine-man-preview+json',\n};\n\n/**\n * GithubAppManager issues and caches tokens for a specific GitHub App.\n */\nclass GithubAppManager {\n private readonly appClient: Octokit;\n private readonly baseUrl?: string;\n private readonly baseAuthConfig: { appId: number; privateKey: string };\n private readonly cache = new Cache();\n private readonly allowedInstallationOwners: string[] | undefined; // undefined allows all installations\n\n constructor(config: GithubAppConfig, baseUrl?: string) {\n this.allowedInstallationOwners = config.allowedInstallationOwners?.map(\n owner => owner.toLocaleLowerCase('en-US'),\n );\n this.baseUrl = baseUrl;\n this.baseAuthConfig = {\n appId: config.appId,\n privateKey: config.privateKey.replace(/\\\\n/gm, '\\n'),\n };\n this.appClient = new Octokit({\n baseUrl,\n headers: HEADERS,\n authStrategy: createAppAuth,\n auth: this.baseAuthConfig,\n });\n }\n\n async getInstallationCredentials(\n owner: string,\n repo?: string,\n ): Promise<{ accessToken: string | undefined }> {\n if (this.allowedInstallationOwners) {\n if (\n !this.allowedInstallationOwners?.includes(\n owner.toLocaleLowerCase('en-US'),\n )\n ) {\n return { accessToken: undefined }; // An empty token allows anonymous access to public repos\n }\n }\n\n // Go and grab an access token for the app scoped to a repository if provided, if not use the organisation installation.\n return this.cache.getOrCreateToken(owner, repo, async () => {\n const { installationId, suspended } = await this.getInstallationData(\n owner,\n );\n if (suspended) {\n throw new Error(`The GitHub application for ${owner} is suspended`);\n }\n\n const result = await this.appClient.apps.createInstallationAccessToken({\n installation_id: installationId,\n headers: HEADERS,\n });\n\n let repositoryNames;\n\n if (result.data.repository_selection === 'selected') {\n const installationClient = new Octokit({\n baseUrl: this.baseUrl,\n auth: result.data.token,\n });\n const repos = await installationClient.paginate(\n installationClient.apps.listReposAccessibleToInstallation,\n );\n // The return type of the paginate method is incorrect.\n const repositories: RestEndpointMethodTypes['apps']['listReposAccessibleToInstallation']['response']['data']['repositories'] =\n repos.repositories ?? repos;\n\n repositoryNames = repositories.map(repository => repository.name);\n }\n return {\n token: result.data.token,\n expiresAt: DateTime.fromISO(result.data.expires_at),\n repositories: repositoryNames,\n };\n });\n }\n\n getInstallations(): Promise<\n RestEndpointMethodTypes['apps']['listInstallations']['response']['data']\n > {\n return this.appClient.paginate(this.appClient.apps.listInstallations);\n }\n\n private async getInstallationData(owner: string): Promise<InstallationData> {\n const allInstallations = await this.getInstallations();\n const installation = allInstallations.find(\n inst =>\n inst.account &&\n 'login' in inst.account &&\n inst.account.login?.toLocaleLowerCase('en-US') ===\n owner.toLocaleLowerCase('en-US'),\n );\n if (installation) {\n return {\n installationId: installation.id,\n suspended: Boolean(installation.suspended_by),\n };\n }\n const notFoundError = new Error(\n `No app installation found for ${owner} in ${this.baseAuthConfig.appId}`,\n );\n notFoundError.name = 'NotFoundError';\n throw notFoundError;\n }\n}\n\n/**\n * Corresponds to a Github installation which internally could hold several GitHub Apps.\n *\n * @public\n */\nexport class GithubAppCredentialsMux {\n private readonly apps: GithubAppManager[];\n\n constructor(config: GithubIntegrationConfig, appIds: number[] = []) {\n this.apps =\n config.apps\n ?.filter(app => (appIds.length ? appIds.includes(app.appId) : true))\n .map(ac => new GithubAppManager(ac, config.apiBaseUrl)) ?? [];\n }\n\n async getAllInstallations(): Promise<\n RestEndpointMethodTypes['apps']['listInstallations']['response']['data']\n > {\n if (!this.apps.length) {\n return [];\n }\n\n const installs = await Promise.all(\n this.apps.map(app => app.getInstallations()),\n );\n\n return installs.flat();\n }\n\n async getAppToken(owner: string, repo?: string): Promise<string | undefined> {\n if (this.apps.length === 0) {\n return undefined;\n }\n\n const results = await Promise.all(\n this.apps.map(app =>\n app.getInstallationCredentials(owner, repo).then(\n credentials => ({ credentials, error: undefined }),\n error => ({ credentials: undefined, error }),\n ),\n ),\n );\n\n const result = results.find(\n resultItem => resultItem.credentials?.accessToken,\n );\n if (result) {\n return result.credentials!.accessToken;\n }\n\n const errors = results.map(r => r.error);\n const notNotFoundError = errors.find(err => err?.name !== 'NotFoundError');\n if (notNotFoundError) {\n throw notNotFoundError;\n }\n\n return undefined;\n }\n}\n\n/**\n * Handles the creation and caching of credentials for GitHub integrations.\n *\n * @public\n * @remarks\n *\n * TODO: Possibly move this to a backend only package so that it's not used in the frontend by mistake\n */\nexport class SingleInstanceGithubCredentialsProvider\n implements GithubCredentialsProvider\n{\n static create: (\n config: GithubIntegrationConfig,\n ) => GithubCredentialsProvider = config => {\n return new SingleInstanceGithubCredentialsProvider(\n new GithubAppCredentialsMux(config),\n config.token,\n );\n };\n\n private readonly githubAppCredentialsMux: GithubAppCredentialsMux;\n private readonly token?: string;\n\n private constructor(\n githubAppCredentialsMux: GithubAppCredentialsMux,\n token?: string,\n ) {\n this.githubAppCredentialsMux = githubAppCredentialsMux;\n this.token = token;\n }\n\n /**\n * Returns {@link GithubCredentials} for a given URL.\n *\n * @remarks\n *\n * Consecutive calls to this method with the same URL will return cached\n * credentials.\n *\n * The shortest lifetime for a token returned is 10 minutes.\n *\n * @example\n * ```ts\n * const { token, headers } = await getCredentials({\n * url: 'github.com/backstage/foobar'\n * })\n * ```\n *\n * @param opts - The organization or repository URL\n * @returns A promise of {@link GithubCredentials}.\n */\n async getCredentials(opts: { url: string }): Promise<GithubCredentials> {\n const parsed = parseGitUrl(opts.url);\n\n const owner = parsed.owner || parsed.name;\n const repo = parsed.owner ? parsed.name : undefined;\n\n let type: GithubCredentialType = 'app';\n let token = await this.githubAppCredentialsMux.getAppToken(owner, repo);\n if (!token) {\n type = 'token';\n token = this.token;\n }\n\n return {\n headers: token ? { Authorization: `Bearer ${token}` } : undefined,\n token,\n type,\n };\n }\n}\n"],"names":[],"mappings":";;;;;AAsCA,MAAM,KAAA,CAAM;AAAA,EACO,UAAA,uBAAiB,GAAA,EAAmC;AAAA,EA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CAAK,uBAAA,GAA0B,uBAAA;AAC/B,IAAA,IAAA,CAAK,KAAA,GAAQ,KAAA;AAAA,EACf;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAsBA,MAAM,eAAe,IAAA,EAAmD;AACtE,IAAA,MAAM,MAAA,GAAS,WAAA,CAAY,IAAA,CAAK,GAAG,CAAA;AAEnC,IAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,KAAA,IAAS,MAAA,CAAO,IAAA;AACrC,IAAA,MAAM,IAAA,GAAO,MAAA,CAAO,KAAA,GAAQ,MAAA,CAAO,IAAA,GAAO,MAAA;AAE1C,IAAA,IAAI,IAAA,GAA6B,KAAA;AACjC,IAAA,IAAI,QAAQ,MAAM,IAAA,CAAK,uBAAA,CAAwB,WAAA,CAAY,OAAO,IAAI,CAAA;AACtE,IAAA,IAAI,CAAC,KAAA,EAAO;AACV,MAAA,IAAA,GAAO,OAAA;AACP,MAAA,KAAA,GAAQ,IAAA,CAAK,KAAA;AAAA,IACf;AAEA,IAAA,OAAO;AAAA,MACL,SAAS,KAAA,GAAQ,EAAE,eAAe,CAAA,OAAA,EAAU,KAAK,IAAG,GAAI,MAAA;AAAA,MACxD,KAAA;AAAA,MACA;AAAA,KACF;AAAA,EACF;AACF;;;;"}
package/dist/index.d.ts CHANGED
@@ -529,6 +529,8 @@ type BitbucketCloudIntegrationConfig = {
529
529
  appPassword?: string;
530
530
  /**
531
531
  * The access token to use for requests to Bitbucket Cloud (bitbucket.org).
532
+ *
533
+ * See https://support.atlassian.com/bitbucket-cloud/docs/api-tokens/
532
534
  */
533
535
  token?: string;
534
536
  /** PGP private key for signing commits. */
@@ -1377,6 +1379,8 @@ declare function getBitbucketCloudDownloadUrl(url: string, config: BitbucketClou
1377
1379
  declare function getBitbucketCloudFileFetchUrl(url: string, config: BitbucketCloudIntegrationConfig): string;
1378
1380
  /**
1379
1381
  * Gets the request options necessary to make requests to a given provider.
1382
+ * Returns headers for authenticating with Bitbucket Cloud.
1383
+ * Supports both username/token and username/appPassword auth.
1380
1384
  *
1381
1385
  * @param config - The relevant provider config
1382
1386
  * @public
@@ -1772,9 +1776,9 @@ declare class GithubAppCredentialsMux {
1772
1776
  * TODO: Possibly move this to a backend only package so that it's not used in the frontend by mistake
1773
1777
  */
1774
1778
  declare class SingleInstanceGithubCredentialsProvider implements GithubCredentialsProvider {
1779
+ static create: (config: GithubIntegrationConfig) => GithubCredentialsProvider;
1775
1780
  private readonly githubAppCredentialsMux;
1776
1781
  private readonly token?;
1777
- static create: (config: GithubIntegrationConfig) => GithubCredentialsProvider;
1778
1782
  private constructor();
1779
1783
  /**
1780
1784
  * Returns {@link GithubCredentials} for a given URL.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@backstage/integration",
3
- "version": "1.18.1",
3
+ "version": "1.18.2",
4
4
  "description": "Helpers for managing integrations towards external systems",
5
5
  "backstage": {
6
6
  "role": "common-library"
@@ -39,7 +39,7 @@
39
39
  "dependencies": {
40
40
  "@azure/identity": "^4.0.0",
41
41
  "@azure/storage-blob": "^12.5.0",
42
- "@backstage/config": "^1.3.5",
42
+ "@backstage/config": "^1.3.6",
43
43
  "@backstage/errors": "^1.2.7",
44
44
  "@octokit/auth-app": "^4.0.0",
45
45
  "@octokit/rest": "^19.0.3",
@@ -49,8 +49,8 @@
49
49
  "luxon": "^3.0.0"
50
50
  },
51
51
  "devDependencies": {
52
- "@backstage/cli": "^0.34.4",
53
- "@backstage/config-loader": "^1.10.5",
52
+ "@backstage/cli": "^0.34.5",
53
+ "@backstage/config-loader": "^1.10.6",
54
54
  "@types/luxon": "^3.0.0",
55
55
  "msw": "^1.0.0"
56
56
  },