@backstage/integration 2.1.2 → 2.1.3-next.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -0
- package/dist/ScmIntegrations.cjs.js.map +1 -1
- package/dist/ScmIntegrations.esm.js.map +1 -1
- package/dist/alpha/github/createGitHubCredentialsProviderFromConnection.cjs.js.map +1 -1
- package/dist/alpha/github/createGitHubCredentialsProviderFromConnection.esm.js.map +1 -1
- package/dist/awsCodeCommit/AwsCodeCommitIntegration.cjs.js +1 -0
- package/dist/awsCodeCommit/AwsCodeCommitIntegration.cjs.js.map +1 -1
- package/dist/awsCodeCommit/AwsCodeCommitIntegration.esm.js +1 -0
- package/dist/awsCodeCommit/AwsCodeCommitIntegration.esm.js.map +1 -1
- package/dist/awsCodeCommit/config.cjs.js.map +1 -1
- package/dist/awsCodeCommit/config.esm.js.map +1 -1
- package/dist/awsS3/AwsS3Integration.cjs.js +1 -0
- package/dist/awsS3/AwsS3Integration.cjs.js.map +1 -1
- package/dist/awsS3/AwsS3Integration.esm.js +1 -0
- package/dist/awsS3/AwsS3Integration.esm.js.map +1 -1
- package/dist/awsS3/config.cjs.js.map +1 -1
- package/dist/awsS3/config.esm.js.map +1 -1
- package/dist/azure/AzureIntegration.cjs.js +12 -1
- package/dist/azure/AzureIntegration.cjs.js.map +1 -1
- package/dist/azure/AzureIntegration.esm.js +12 -1
- package/dist/azure/AzureIntegration.esm.js.map +1 -1
- package/dist/azure/AzureUrl.cjs.js.map +1 -1
- package/dist/azure/AzureUrl.esm.js.map +1 -1
- package/dist/azure/CachedAzureDevOpsCredentialsProvider.cjs.js +1 -0
- package/dist/azure/CachedAzureDevOpsCredentialsProvider.cjs.js.map +1 -1
- package/dist/azure/CachedAzureDevOpsCredentialsProvider.esm.js +1 -0
- package/dist/azure/CachedAzureDevOpsCredentialsProvider.esm.js.map +1 -1
- package/dist/azure/DefaultAzureDevOpsCredentialsProvider.cjs.js +1 -0
- package/dist/azure/DefaultAzureDevOpsCredentialsProvider.cjs.js.map +1 -1
- package/dist/azure/DefaultAzureDevOpsCredentialsProvider.esm.js +1 -0
- package/dist/azure/DefaultAzureDevOpsCredentialsProvider.esm.js.map +1 -1
- package/dist/azure/ManagedIdentityClientAssertion.cjs.js.map +1 -1
- package/dist/azure/ManagedIdentityClientAssertion.esm.js.map +1 -1
- package/dist/azure/config.cjs.js.map +1 -1
- package/dist/azure/config.esm.js.map +1 -1
- package/dist/azure/core.cjs.js.map +1 -1
- package/dist/azure/core.esm.js.map +1 -1
- package/dist/azure/isVisualStudioDomain.cjs.js.map +1 -1
- package/dist/azure/isVisualStudioDomain.esm.js.map +1 -1
- package/dist/azureBlobStorage/AzureBlobStorageIntegration.cjs.js +1 -0
- package/dist/azureBlobStorage/AzureBlobStorageIntegration.cjs.js.map +1 -1
- package/dist/azureBlobStorage/AzureBlobStorageIntegration.esm.js +1 -0
- package/dist/azureBlobStorage/AzureBlobStorageIntegration.esm.js.map +1 -1
- package/dist/azureBlobStorage/DefaultAzureCredentialsProvider.cjs.js +1 -0
- package/dist/azureBlobStorage/DefaultAzureCredentialsProvider.cjs.js.map +1 -1
- package/dist/azureBlobStorage/DefaultAzureCredentialsProvider.esm.js +1 -0
- package/dist/azureBlobStorage/DefaultAzureCredentialsProvider.esm.js.map +1 -1
- package/dist/azureBlobStorage/config.cjs.js.map +1 -1
- package/dist/azureBlobStorage/config.esm.js.map +1 -1
- package/dist/bitbucketCloud/BitbucketCloudIntegration.cjs.js +1 -0
- package/dist/bitbucketCloud/BitbucketCloudIntegration.cjs.js.map +1 -1
- package/dist/bitbucketCloud/BitbucketCloudIntegration.esm.js +1 -0
- package/dist/bitbucketCloud/BitbucketCloudIntegration.esm.js.map +1 -1
- package/dist/bitbucketCloud/config.cjs.js.map +1 -1
- package/dist/bitbucketCloud/config.esm.js.map +1 -1
- package/dist/bitbucketCloud/core.cjs.js +14 -10
- package/dist/bitbucketCloud/core.cjs.js.map +1 -1
- package/dist/bitbucketCloud/core.esm.js +14 -10
- package/dist/bitbucketCloud/core.esm.js.map +1 -1
- package/dist/bitbucketServer/BitbucketServerIntegration.cjs.js +1 -0
- package/dist/bitbucketServer/BitbucketServerIntegration.cjs.js.map +1 -1
- package/dist/bitbucketServer/BitbucketServerIntegration.esm.js +1 -0
- package/dist/bitbucketServer/BitbucketServerIntegration.esm.js.map +1 -1
- package/dist/bitbucketServer/config.cjs.js.map +1 -1
- package/dist/bitbucketServer/config.esm.js.map +1 -1
- package/dist/bitbucketServer/core.cjs.js.map +1 -1
- package/dist/bitbucketServer/core.esm.js.map +1 -1
- package/dist/gerrit/GerritIntegration.cjs.js +1 -0
- package/dist/gerrit/GerritIntegration.cjs.js.map +1 -1
- package/dist/gerrit/GerritIntegration.esm.js +1 -0
- package/dist/gerrit/GerritIntegration.esm.js.map +1 -1
- package/dist/gerrit/config.cjs.js.map +1 -1
- package/dist/gerrit/config.esm.js.map +1 -1
- package/dist/gerrit/core.cjs.js.map +1 -1
- package/dist/gerrit/core.esm.js.map +1 -1
- package/dist/gitea/GiteaIntegration.cjs.js +1 -0
- package/dist/gitea/GiteaIntegration.cjs.js.map +1 -1
- package/dist/gitea/GiteaIntegration.esm.js +1 -0
- package/dist/gitea/GiteaIntegration.esm.js.map +1 -1
- package/dist/gitea/config.cjs.js.map +1 -1
- package/dist/gitea/config.esm.js.map +1 -1
- package/dist/gitea/core.cjs.js.map +1 -1
- package/dist/gitea/core.esm.js.map +1 -1
- package/dist/github/DefaultGithubCredentialsProvider.cjs.js.map +1 -1
- package/dist/github/DefaultGithubCredentialsProvider.esm.js.map +1 -1
- package/dist/github/GithubIntegration.cjs.js +1 -0
- package/dist/github/GithubIntegration.cjs.js.map +1 -1
- package/dist/github/GithubIntegration.esm.js +1 -0
- package/dist/github/GithubIntegration.esm.js.map +1 -1
- package/dist/github/SingleInstanceGithubCredentialsProvider.cjs.js.map +1 -1
- package/dist/github/SingleInstanceGithubCredentialsProvider.esm.js.map +1 -1
- package/dist/github/config.cjs.js.map +1 -1
- package/dist/github/config.esm.js.map +1 -1
- package/dist/github/core.cjs.js.map +1 -1
- package/dist/github/core.esm.js.map +1 -1
- package/dist/gitlab/DefaultGitlabCredentialsProvider.cjs.js +1 -0
- package/dist/gitlab/DefaultGitlabCredentialsProvider.cjs.js.map +1 -1
- package/dist/gitlab/DefaultGitlabCredentialsProvider.esm.js +1 -0
- package/dist/gitlab/DefaultGitlabCredentialsProvider.esm.js.map +1 -1
- package/dist/gitlab/GitLabIntegration.cjs.js +1 -0
- package/dist/gitlab/GitLabIntegration.cjs.js.map +1 -1
- package/dist/gitlab/GitLabIntegration.esm.js +1 -0
- package/dist/gitlab/GitLabIntegration.esm.js.map +1 -1
- package/dist/gitlab/SingleInstanceGitlabCredentialsProvider.cjs.js +1 -0
- package/dist/gitlab/SingleInstanceGitlabCredentialsProvider.cjs.js.map +1 -1
- package/dist/gitlab/SingleInstanceGitlabCredentialsProvider.esm.js +1 -0
- package/dist/gitlab/SingleInstanceGitlabCredentialsProvider.esm.js.map +1 -1
- package/dist/gitlab/config.cjs.js.map +1 -1
- package/dist/gitlab/config.esm.js.map +1 -1
- package/dist/gitlab/core.cjs.js.map +1 -1
- package/dist/gitlab/core.esm.js.map +1 -1
- package/dist/googleGcs/GoogleGcsIntegration.cjs.js +1 -0
- package/dist/googleGcs/GoogleGcsIntegration.cjs.js.map +1 -1
- package/dist/googleGcs/GoogleGcsIntegration.esm.js +1 -0
- package/dist/googleGcs/GoogleGcsIntegration.esm.js.map +1 -1
- package/dist/googleGcs/config.cjs.js.map +1 -1
- package/dist/googleGcs/config.esm.js.map +1 -1
- package/dist/harness/HarnessIntegration.cjs.js +1 -0
- package/dist/harness/HarnessIntegration.cjs.js.map +1 -1
- package/dist/harness/HarnessIntegration.esm.js +1 -0
- package/dist/harness/HarnessIntegration.esm.js.map +1 -1
- package/dist/harness/config.cjs.js.map +1 -1
- package/dist/harness/config.esm.js.map +1 -1
- package/dist/harness/core.cjs.js.map +1 -1
- package/dist/harness/core.esm.js.map +1 -1
- package/dist/helpers.cjs.js.map +1 -1
- package/dist/helpers.esm.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/package.json +7 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core.esm.js","sources":["../../src/gitea/core.ts"],"sourcesContent":["/*\n * Copyright 2022 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 */\nimport { GiteaIntegrationConfig } from './config';\n\n/**\n * Given a URL pointing to a file, returns a URL\n * for editing the contents of the data.\n *\n * @remarks\n *\n * Converts\n * from: https://gitea.com/a/b/src/branchname/path/to/c.yaml\n * or: https://gitea.com/a/b/_edit/branchname/path/to/c.yaml\n *\n * @param url - A URL pointing to a file\n * @param config - The relevant provider config\n * @public\n */\nexport function getGiteaEditContentsUrl(\n config: GiteaIntegrationConfig,\n url: string,\n) {\n const giteaUrl = parseGiteaUrl(config, url);\n return `${giteaUrl.url}/${giteaUrl.owner}/${giteaUrl.name}/_edit/${giteaUrl.ref}/${giteaUrl.path}`;\n}\n\n/**\n * Given a URL pointing to a file, returns an api URL\n * for fetching the contents of the data.\n *\n * @remarks\n *\n * Converts\n * from: https://gitea.com/a/b/src/branch/branchname/path/to/c.yaml\n * to: https://gitea.com/api/v1/repos/a/b/contents/path/to/c.yaml?ref=branchname\n *\n * @param url - A URL pointing to a file\n * @param config - The relevant provider config\n * @public\n */\nexport function getGiteaFileContentsUrl(\n config: GiteaIntegrationConfig,\n url: string,\n) {\n const giteaUrl = parseGiteaUrl(config, url);\n return `${giteaUrl.url}/api/v1/repos/${giteaUrl.owner}/${giteaUrl.name}/contents/${giteaUrl.path}?ref=${giteaUrl.ref}`;\n}\n\n/**\n * Given a URL pointing to a repository/path, returns a URL\n * for archive contents of the repository.\n *\n * @remarks\n *\n * Converts\n * from: https://gitea.com/a/b/src/branchname\n * or: https://gitea.com/api/v1/repos/a/b/archive/branchname.tar.gz\n *\n * @param url - A URL pointing to a repository/path\n * @param config - The relevant provider config\n * @public\n */\nexport function getGiteaArchiveUrl(\n config: GiteaIntegrationConfig,\n url: string,\n) {\n const giteaUrl = parseGiteaUrl(config, url);\n return `${giteaUrl.url}/api/v1/repos/${giteaUrl.owner}/${giteaUrl.name}/archive/${giteaUrl.ref}.tar.gz`;\n}\n\n/**\n * Given a URL pointing to a repository branch, returns a URL\n * for latest commit information.\n *\n * @remarks\n *\n * Converts\n * from: https://gitea.com/a/b/src/branchname\n * or: https://gitea.com/api/v1/repos/a/b/git/commits/branchname\n *\n * @param url - A URL pointing to a repository branch\n * @param config - The relevant provider config\n * @public\n */\nexport function getGiteaLatestCommitUrl(\n config: GiteaIntegrationConfig,\n url: string,\n) {\n const giteaUrl = parseGiteaUrl(config, url);\n return `${giteaUrl.url}/api/v1/repos/${giteaUrl.owner}/${giteaUrl.name}/git/commits/${giteaUrl.ref}`;\n}\n\n/**\n * Return request headers for a Gitea provider.\n *\n * @param config - A Gitea provider config\n * @public\n */\nexport function getGiteaRequestOptions(config: GiteaIntegrationConfig): {\n headers?: Record<string, string>;\n} {\n const headers: Record<string, string> = {};\n const { username, password } = config;\n\n if (!password) {\n return headers;\n }\n\n if (username) {\n headers.Authorization = `basic ${Buffer.from(\n `${username}:${password}`,\n ).toString('base64')}`;\n } else {\n headers.Authorization = `token ${password}`;\n }\n\n return {\n headers,\n };\n}\n\n/**\n * Return parsed git url properties.\n *\n * @param config - A Gitea provider config\n * @param url - A URL pointing to a repository\n * @public\n */\nexport function parseGiteaUrl(\n config: GiteaIntegrationConfig,\n url: string,\n): {\n url: string;\n owner: string;\n name: string;\n ref: string;\n path: string;\n} {\n const baseUrl = config.baseUrl ?? `https://${config.host}`;\n try {\n const [_blank, owner, name, _src, _branch, ref, ...path] = url\n .replace(baseUrl, '')\n .split('/');\n const pathWithoutSlash = path.join('/').replace(/^\\//, '');\n\n return {\n url: baseUrl,\n owner: owner,\n name: name,\n ref: ref,\n path: pathWithoutSlash,\n };\n } catch (e) {\n throw new Error(`Incorrect URL: ${url}, ${e}`);\n }\n}\n"],"names":[],"mappings":"AA+BO,SAAS,uBAAA,CACd,QACA,GAAA,EACA;AACA,EAAA,MAAM,QAAA,GAAW,aAAA,CAAc,MAAA,EAAQ,GAAG,CAAA;AAC1C,EAAA,OAAO,CAAA,EAAG,QAAA,CAAS,GAAG,CAAA,CAAA,EAAI,SAAS,KAAK,CAAA,CAAA,EAAI,QAAA,CAAS,IAAI,CAAA,OAAA,EAAU,QAAA,CAAS,GAAG,CAAA,CAAA,EAAI,SAAS,IAAI,CAAA,CAAA;AAClG;AAgBO,SAAS,uBAAA,CACd,QACA,GAAA,EACA;AACA,EAAA,MAAM,QAAA,GAAW,aAAA,CAAc,MAAA,EAAQ,GAAG,CAAA;AAC1C,EAAA,OAAO,CAAA,EAAG,QAAA,CAAS,GAAG,CAAA,cAAA,EAAiB,SAAS,KAAK,CAAA,CAAA,EAAI,QAAA,CAAS,IAAI,CAAA,UAAA,EAAa,QAAA,CAAS,IAAI,CAAA,KAAA,EAAQ,SAAS,GAAG,CAAA,CAAA;AACtH;AAgBO,SAAS,kBAAA,CACd,QACA,GAAA,EACA;AACA,EAAA,MAAM,QAAA,GAAW,aAAA,CAAc,MAAA,EAAQ,GAAG,CAAA;AAC1C,EAAA,OAAO,CAAA,EAAG,QAAA,CAAS,GAAG,CAAA,cAAA,EAAiB,QAAA,CAAS,KAAK,CAAA,CAAA,EAAI,QAAA,CAAS,IAAI,CAAA,SAAA,EAAY,QAAA,CAAS,GAAG,CAAA,OAAA,CAAA;AAChG;AAgBO,SAAS,uBAAA,CACd,QACA,GAAA,EACA;AACA,EA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OAAO;AAAA,MACL,GAAA,EAAK,OAAA;AAAA,MACL,KAAA;AAAA,MACA,IAAA;AAAA,MACA,GAAA;AAAA,MACA,IAAA,EAAM;AAAA,KACR;AAAA,EACF,SAAS,CAAA,EAAG;AACV,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,eAAA,EAAkB,GAAG,CAAA,EAAA,EAAK,CAAC,CAAA,CAAE,CAAA;AAAA,EAC/C;AACF
|
|
1
|
+
{"version":3,"file":"core.esm.js","sources":["../../src/gitea/core.ts"],"sourcesContent":["/*\n * Copyright 2022 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 */\nimport { GiteaIntegrationConfig } from './config';\n\n/**\n * Given a URL pointing to a file, returns a URL\n * for editing the contents of the data.\n *\n * @remarks\n *\n * Converts\n * from: https://gitea.com/a/b/src/branchname/path/to/c.yaml\n * or: https://gitea.com/a/b/_edit/branchname/path/to/c.yaml\n *\n * @param url - A URL pointing to a file\n * @param config - The relevant provider config\n * @public\n */\nexport function getGiteaEditContentsUrl(\n config: GiteaIntegrationConfig,\n url: string,\n) {\n const giteaUrl = parseGiteaUrl(config, url);\n return `${giteaUrl.url}/${giteaUrl.owner}/${giteaUrl.name}/_edit/${giteaUrl.ref}/${giteaUrl.path}`;\n}\n\n/**\n * Given a URL pointing to a file, returns an api URL\n * for fetching the contents of the data.\n *\n * @remarks\n *\n * Converts\n * from: https://gitea.com/a/b/src/branch/branchname/path/to/c.yaml\n * to: https://gitea.com/api/v1/repos/a/b/contents/path/to/c.yaml?ref=branchname\n *\n * @param url - A URL pointing to a file\n * @param config - The relevant provider config\n * @public\n */\nexport function getGiteaFileContentsUrl(\n config: GiteaIntegrationConfig,\n url: string,\n) {\n const giteaUrl = parseGiteaUrl(config, url);\n return `${giteaUrl.url}/api/v1/repos/${giteaUrl.owner}/${giteaUrl.name}/contents/${giteaUrl.path}?ref=${giteaUrl.ref}`;\n}\n\n/**\n * Given a URL pointing to a repository/path, returns a URL\n * for archive contents of the repository.\n *\n * @remarks\n *\n * Converts\n * from: https://gitea.com/a/b/src/branchname\n * or: https://gitea.com/api/v1/repos/a/b/archive/branchname.tar.gz\n *\n * @param url - A URL pointing to a repository/path\n * @param config - The relevant provider config\n * @public\n */\nexport function getGiteaArchiveUrl(\n config: GiteaIntegrationConfig,\n url: string,\n) {\n const giteaUrl = parseGiteaUrl(config, url);\n return `${giteaUrl.url}/api/v1/repos/${giteaUrl.owner}/${giteaUrl.name}/archive/${giteaUrl.ref}.tar.gz`;\n}\n\n/**\n * Given a URL pointing to a repository branch, returns a URL\n * for latest commit information.\n *\n * @remarks\n *\n * Converts\n * from: https://gitea.com/a/b/src/branchname\n * or: https://gitea.com/api/v1/repos/a/b/git/commits/branchname\n *\n * @param url - A URL pointing to a repository branch\n * @param config - The relevant provider config\n * @public\n */\nexport function getGiteaLatestCommitUrl(\n config: GiteaIntegrationConfig,\n url: string,\n) {\n const giteaUrl = parseGiteaUrl(config, url);\n return `${giteaUrl.url}/api/v1/repos/${giteaUrl.owner}/${giteaUrl.name}/git/commits/${giteaUrl.ref}`;\n}\n\n/**\n * Return request headers for a Gitea provider.\n *\n * @param config - A Gitea provider config\n * @public\n */\nexport function getGiteaRequestOptions(config: GiteaIntegrationConfig): {\n headers?: Record<string, string>;\n} {\n const headers: Record<string, string> = {};\n const { username, password } = config;\n\n if (!password) {\n return headers;\n }\n\n if (username) {\n headers.Authorization = `basic ${Buffer.from(\n `${username}:${password}`,\n ).toString('base64')}`;\n } else {\n headers.Authorization = `token ${password}`;\n }\n\n return {\n headers,\n };\n}\n\n/**\n * Return parsed git url properties.\n *\n * @param config - A Gitea provider config\n * @param url - A URL pointing to a repository\n * @public\n */\nexport function parseGiteaUrl(\n config: GiteaIntegrationConfig,\n url: string,\n): {\n url: string;\n owner: string;\n name: string;\n ref: string;\n path: string;\n} {\n const baseUrl = config.baseUrl ?? `https://${config.host}`;\n try {\n const [_blank, owner, name, _src, _branch, ref, ...path] = url\n .replace(baseUrl, '')\n .split('/');\n const pathWithoutSlash = path.join('/').replace(/^\\//, '');\n\n return {\n url: baseUrl,\n owner: owner,\n name: name,\n ref: ref,\n path: pathWithoutSlash,\n };\n } catch (e) {\n throw new Error(`Incorrect URL: ${url}, ${e}`);\n }\n}\n"],"names":[],"mappings":"AA+BO,SAAS,uBAAA,CACd,QACA,GAAA,EACA;AACA,EAAA,MAAM,QAAA,GAAW,aAAA,CAAc,MAAA,EAAQ,GAAG,CAAA;AAC1C,EAAA,OAAO,CAAA,EAAG,QAAA,CAAS,GAAG,CAAA,CAAA,EAAI,SAAS,KAAK,CAAA,CAAA,EAAI,QAAA,CAAS,IAAI,CAAA,OAAA,EAAU,QAAA,CAAS,GAAG,CAAA,CAAA,EAAI,SAAS,IAAI,CAAA,CAAA;AAClG;AAgBO,SAAS,uBAAA,CACd,QACA,GAAA,EACA;AACA,EAAA,MAAM,QAAA,GAAW,aAAA,CAAc,MAAA,EAAQ,GAAG,CAAA;AAC1C,EAAA,OAAO,CAAA,EAAG,QAAA,CAAS,GAAG,CAAA,cAAA,EAAiB,SAAS,KAAK,CAAA,CAAA,EAAI,QAAA,CAAS,IAAI,CAAA,UAAA,EAAa,QAAA,CAAS,IAAI,CAAA,KAAA,EAAQ,SAAS,GAAG,CAAA,CAAA;AACtH;AAgBO,SAAS,kBAAA,CACd,QACA,GAAA,EACA;AACA,EAAA,MAAM,QAAA,GAAW,aAAA,CAAc,MAAA,EAAQ,GAAG,CAAA;AAC1C,EAAA,OAAO,CAAA,EAAG,QAAA,CAAS,GAAG,CAAA,cAAA,EAAiB,QAAA,CAAS,KAAK,CAAA,CAAA,EAAI,QAAA,C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CAAA;AACZ,IAAA,MAAM,mBAAmB,IAAA,CAAK,IAAA,CAAK,GAAG,CAAA,CAAE,OAAA,CAAQ,OAAO,EAAE,CAAA;AAEzD,IAAA,OAAO;AAAA,MACL,GAAA,EAAK,OAAA;AAAA,MACL,KAAA;AAAA,MACA,IAAA;AAAA,MACA,GAAA;AAAA,MACA,IAAA,EAAM;AAAA,KACR;AAAA,EACF,SAAS,CAAA,EAAG;AACV,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,eAAA,EAAkB,GAAG,CAAA,EAAA,EAAK,CAAC,CAAA,CAAE,CAAA;AAAA,EAC/C;AACF;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DefaultGithubCredentialsProvider.cjs.js","sources":["../../src/github/DefaultGithubCredentialsProvider.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 { GithubCredentials, GithubCredentialsProvider } from './types';\nimport { ScmIntegrationRegistry } from '../registry';\nimport { SingleInstanceGithubCredentialsProvider } from './SingleInstanceGithubCredentialsProvider';\nimport type { ConnectionsService } from '@backstage/connections';\nimport { ForwardedError, InputError } from '@backstage/errors';\nimport type { GithubIntegrationConfig } from './config';\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 DefaultGithubCredentialsProvider\n implements GithubCredentialsProvider\n{\n static fromIntegrations(integrations: ScmIntegrationRegistry) {\n const credentialsProviders: Map<string, GithubCredentialsProvider> =\n new Map<string, GithubCredentialsProvider>();\n\n integrations.github.list().forEach(integration => {\n const credentialsProvider =\n SingleInstanceGithubCredentialsProvider.create(integration.config);\n credentialsProviders.set(integration.config.host, credentialsProvider);\n });\n return new DefaultGithubCredentialsProvider(credentialsProviders);\n }\n\n /**\n * Creates a credentials provider backed by the connections service.\n *\n * @param connections - The connections service used to resolve GitHub credentials.\n * @internal\n */\n static experimentalFromConnections(connections: ConnectionsService) {\n return new DefaultGithubCredentialsProvider(\n new Map<string, GithubCredentialsProvider>(),\n connections,\n );\n }\n\n private readonly providers: Map<string, GithubCredentialsProvider>;\n readonly #connections?: ConnectionsService;\n\n private constructor(\n providers: Map<string, GithubCredentialsProvider>,\n connections?: ConnectionsService,\n ) {\n this.providers = providers;\n this.#connections = connections;\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: 'https://github.com/backstage/foobar'\n * })\n *\n * const { token, headers } = await getCredentials({\n * url: 'https://github.com/backstage'\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 if (this.#connections) {\n // Ask the connections service to select auth for this URL. A host may\n // have different GitHub Apps for different organizations, so this\n // selection cannot be done once when the provider is created.\n\n const connection = await this.#connections\n .find({\n type: 'github',\n query: { url: opts.url },\n authMethods: ['app', 'token', 'none'],\n })\n .catch(error => {\n throw new ForwardedError(\n 'Failed getting credentials from connection',\n error,\n );\n });\n\n const { auth } = connection;\n\n // Adapt the connection schema to the existing provider configuration so\n // credential creation and token caching stay in one implementation.\n const config: GithubIntegrationConfig = {\n host: connection.host,\n apiBaseUrl: connection.apiBaseUrl,\n rawBaseUrl: connection.rawBaseUrl,\n };\n\n // Reusing an App provider preserves its installation-token cache. App\n // organizations are canonicalized because GitHub owner matching is\n // case-insensitive and does not depend on ordering. Static token\n // providers have no internal token cache, so they are recreated rather\n // than placing their secret token in a cache key.\n let providerKey: string | undefined;\n if (auth.method === 'app') {\n const appId = Number(auth.appId);\n if (!Number.isSafeInteger(appId) || appId <= 0) {\n throw new InputError(\n `Invalid GitHub App ID \"${auth.appId}\", expected a positive safe integer`,\n );\n }\n const normalizedOrgs = auth.orgs?.length\n ? Array.from(new Set(auth.orgs.map(org => org.toLowerCase()))).sort()\n : undefined;\n config.apps = [\n {\n appId,\n privateKey: auth.privateKey,\n clientId: auth.clientId,\n clientSecret: auth.clientSecret,\n webhookSecret: auth.webhookSecret,\n publicAccess: auth.publicAccess,\n allowedInstallationOwners: normalizedOrgs,\n },\n ];\n providerKey = `${connection.host}:app:${appId}:${JSON.stringify(\n normalizedOrgs ?? [],\n )}:${String(auth.publicAccess ?? false)}`;\n } else if (auth.method === 'token') {\n config.token = auth.token;\n } else {\n providerKey = `${connection.host}:none`;\n }\n\n let provider = providerKey ? this.providers.get(providerKey) : undefined;\n if (!provider) {\n provider = SingleInstanceGithubCredentialsProvider.create(config);\n if (providerKey) {\n this.providers.set(providerKey, provider);\n }\n }\n\n return provider.getCredentials(opts);\n }\n\n const parsed = new URL(opts.url);\n const provider = this.providers.get(parsed.host);\n\n if (!provider) {\n throw new Error(\n `There is no GitHub integration that matches ${opts.url}. Please add a configuration for an integration.`,\n );\n }\n\n return provider.getCredentials(opts);\n }\n}\n"],"names":["SingleInstanceGithubCredentialsProvider","ForwardedError","InputError","provider"],"mappings":";;;;;AA+BO,MAAM,gCAAA,CAEb;AAAA,EACE,OAAO,iBAAiB,YAAA,EAAsC;AAC5D,IAAA,MAAM,oBAAA,uBACA,GAAA,EAAuC;AAE7C,IAAA,YAAA,CAAa,MAAA,CAAO,IAAA,EAAK,CAAE,OAAA,CAAQ,CAAA,WAAA,KAAe;AAChD,MAAA,MAAM,mBAAA,GACJA,+EAAA,CAAwC,MAAA,CAAO,WAAA,CAAY,MAA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tB,CAAA,MAAO;AACL,QAAA,WAAA,GAAc,CAAA,EAAG,WAAW,IAAI,CAAA,KAAA,CAAA;AAAA,MAClC;AAEA,MAAA,IAAIC,YAAW,WAAA,GAAc,IAAA,CAAK,SAAA,CAAU,GAAA,CAAI,WAAW,CAAA,GAAI,MAAA;AAC/D,MAAA,IAAI,CAACA,SAAAA,EAAU;AACb,QAAAA,SAAAA,GAAWH,+EAAA,CAAwC,MAAA,CAAO,MAAM,CAAA;AAChE,QAAA,IAAI,WAAA,EAAa;AACf,UAAA,IAAA,CAAK,SAAA,CAAU,GAAA,CAAI,WAAA,EAAaG,SAAQ,CAAA;AAAA,QAC1C;AAAA,MACF;AAEA,MAAA,OAAOA,SAAAA,CAAS,eAAe,IAAI,CAAA;AAAA,IACrC;AAEA,IAAA,MAAM,MAAA,GAAS,IAAI,GAAA,CAAI,IAAA,CAAK,GAAG,CAAA;AAC/B,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,SAAA,CAAU,GAAA,CAAI,OAAO,IAAI,CAAA;AAE/C,IAAA,IAAI,CAAC,QAAA,EAAU;AACb,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,CAAA,4CAAA,EAA+C,KAAK,GAAG,CAAA,gDAAA;AAAA,OACzD;AAAA,IACF;AAEA,IAAA,OAAO,QAAA,CAAS,eAAe,IAAI,CAAA;AAAA,EACrC;AACF
|
|
1
|
+
{"version":3,"file":"DefaultGithubCredentialsProvider.cjs.js","sources":["../../src/github/DefaultGithubCredentialsProvider.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 { GithubCredentials, GithubCredentialsProvider } from './types';\nimport { ScmIntegrationRegistry } from '../registry';\nimport { SingleInstanceGithubCredentialsProvider } from './SingleInstanceGithubCredentialsProvider';\nimport type { ConnectionsService } from '@backstage/connections';\nimport { ForwardedError, InputError } from '@backstage/errors';\nimport type { GithubIntegrationConfig } from './config';\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 DefaultGithubCredentialsProvider\n implements GithubCredentialsProvider\n{\n static fromIntegrations(integrations: ScmIntegrationRegistry) {\n const credentialsProviders: Map<string, GithubCredentialsProvider> =\n new Map<string, GithubCredentialsProvider>();\n\n integrations.github.list().forEach(integration => {\n const credentialsProvider =\n SingleInstanceGithubCredentialsProvider.create(integration.config);\n credentialsProviders.set(integration.config.host, credentialsProvider);\n });\n return new DefaultGithubCredentialsProvider(credentialsProviders);\n }\n\n /**\n * Creates a credentials provider backed by the connections service.\n *\n * @param connections - The connections service used to resolve GitHub credentials.\n * @internal\n */\n static experimentalFromConnections(connections: ConnectionsService) {\n return new DefaultGithubCredentialsProvider(\n new Map<string, GithubCredentialsProvider>(),\n connections,\n );\n }\n\n private readonly providers: Map<string, GithubCredentialsProvider>;\n readonly #connections?: ConnectionsService;\n\n private constructor(\n providers: Map<string, GithubCredentialsProvider>,\n connections?: ConnectionsService,\n ) {\n this.providers = providers;\n this.#connections = connections;\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: 'https://github.com/backstage/foobar'\n * })\n *\n * const { token, headers } = await getCredentials({\n * url: 'https://github.com/backstage'\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 if (this.#connections) {\n // Ask the connections service to select auth for this URL. A host may\n // have different GitHub Apps for different organizations, so this\n // selection cannot be done once when the provider is created.\n\n const connection = await this.#connections\n .find({\n type: 'github',\n query: { url: opts.url },\n authMethods: ['app', 'token', 'none'],\n })\n .catch(error => {\n throw new ForwardedError(\n 'Failed getting credentials from connection',\n error,\n );\n });\n\n const { auth } = connection;\n\n // Adapt the connection schema to the existing provider configuration so\n // credential creation and token caching stay in one implementation.\n const config: GithubIntegrationConfig = {\n host: connection.host,\n apiBaseUrl: connection.apiBaseUrl,\n rawBaseUrl: connection.rawBaseUrl,\n };\n\n // Reusing an App provider preserves its installation-token cache. App\n // organizations are canonicalized because GitHub owner matching is\n // case-insensitive and does not depend on ordering. Static token\n // providers have no internal token cache, so they are recreated rather\n // than placing their secret token in a cache key.\n let providerKey: string | undefined;\n if (auth.method === 'app') {\n const appId = Number(auth.appId);\n if (!Number.isSafeInteger(appId) || appId <= 0) {\n throw new InputError(\n `Invalid GitHub App ID \"${auth.appId}\", expected a positive safe integer`,\n );\n }\n const normalizedOrgs = auth.orgs?.length\n ? Array.from(new Set(auth.orgs.map(org => org.toLowerCase()))).sort()\n : undefined;\n config.apps = [\n {\n appId,\n privateKey: auth.privateKey,\n clientId: auth.clientId,\n clientSecret: auth.clientSecret,\n webhookSecret: auth.webhookSecret,\n publicAccess: auth.publicAccess,\n allowedInstallationOwners: normalizedOrgs,\n },\n ];\n providerKey = `${connection.host}:app:${appId}:${JSON.stringify(\n normalizedOrgs ?? [],\n )}:${String(auth.publicAccess ?? false)}`;\n } else if (auth.method === 'token') {\n config.token = auth.token;\n } else {\n providerKey = `${connection.host}:none`;\n }\n\n let provider = providerKey ? this.providers.get(providerKey) : undefined;\n if (!provider) {\n provider = SingleInstanceGithubCredentialsProvider.create(config);\n if (providerKey) {\n this.providers.set(providerKey, provider);\n }\n }\n\n return provider.getCredentials(opts);\n }\n\n const parsed = new URL(opts.url);\n const provider = this.providers.get(parsed.host);\n\n if (!provider) {\n throw new Error(\n `There is no GitHub integration that matches ${opts.url}. Please add a configuration for an integration.`,\n );\n }\n\n return provider.getCredentials(opts);\n }\n}\n"],"names":["SingleInstanceGithubCredentialsProvider","ForwardedError","InputError","provider"],"mappings":";;;;;AA+BO,MAAM,gCAAA,CAEb;AAAA,EACE,OAAO,iBAAiB,YAAA,EAAsC;AAC5D,IAAA,MAAM,oBAAA,uBACA,GAAA,EAAuC;AAE7C,IAAA,YAAA,CAAa,MAAA,CAAO,IAAA,EAAK,CAAE,OAAA,CAAQ,CAAA,WAAA,KAAe;AAChD,MAAA,MAAM,mBAAA,GACJA,+EAAA,CAAwC,MAAA,CAAO,WAAA,CAAY,MAAM,CAAA;AACnE,MAAA,oBAAA,CAAqB,GAAA,CAAI,WAAA,CAAY,MAAA,CAAO,IAAA,EAAM,mBAAmB,CAAA;AAAA,IACvE,CAAC,CAAA;AACD,IAAA,OAAO,IAAI,iCAAiC,oBAAoB,CAAA;AAAA,EAClE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,OAAO,4BAA4B,WAAA,EAAiC;AAClE,IAAA,OAAO,IAAI,gCAAA;AAAA,0BACL,GAAA,EAAuC;AAAA,MAC3C;AAAA,KACF;AAAA,EACF;AAAA,EAEiB,SAAA;AAAA,EACR,YAAA;AAAA,EAED,WAAA,CACN,WACA,WAAA,EACA;AACA,IAAA,IAAA,CAAK,SAAA,GAAY,SAAA;AACjB,IAAA,IAAA,CAAK,YAAA,GAAe,WAAA;AAAA,EACtB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA0BA,MAAM,eAAe,IAAA,EAAmD;AACtE,IAAA,IAAI,KAAK,YAAA,EAAc;AAKrB,MAAA,MAAM,UAAA,GAAa,MAAM,IAAA,CAAK,YAAA,CAC3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AAA,OAAO,QAAA,CAAS,eAAe,IAAI,CAAA;AAAA,EACrC;AACF;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DefaultGithubCredentialsProvider.esm.js","sources":["../../src/github/DefaultGithubCredentialsProvider.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 { GithubCredentials, GithubCredentialsProvider } from './types';\nimport { ScmIntegrationRegistry } from '../registry';\nimport { SingleInstanceGithubCredentialsProvider } from './SingleInstanceGithubCredentialsProvider';\nimport type { ConnectionsService } from '@backstage/connections';\nimport { ForwardedError, InputError } from '@backstage/errors';\nimport type { GithubIntegrationConfig } from './config';\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 DefaultGithubCredentialsProvider\n implements GithubCredentialsProvider\n{\n static fromIntegrations(integrations: ScmIntegrationRegistry) {\n const credentialsProviders: Map<string, GithubCredentialsProvider> =\n new Map<string, GithubCredentialsProvider>();\n\n integrations.github.list().forEach(integration => {\n const credentialsProvider =\n SingleInstanceGithubCredentialsProvider.create(integration.config);\n credentialsProviders.set(integration.config.host, credentialsProvider);\n });\n return new DefaultGithubCredentialsProvider(credentialsProviders);\n }\n\n /**\n * Creates a credentials provider backed by the connections service.\n *\n * @param connections - The connections service used to resolve GitHub credentials.\n * @internal\n */\n static experimentalFromConnections(connections: ConnectionsService) {\n return new DefaultGithubCredentialsProvider(\n new Map<string, GithubCredentialsProvider>(),\n connections,\n );\n }\n\n private readonly providers: Map<string, GithubCredentialsProvider>;\n readonly #connections?: ConnectionsService;\n\n private constructor(\n providers: Map<string, GithubCredentialsProvider>,\n connections?: ConnectionsService,\n ) {\n this.providers = providers;\n this.#connections = connections;\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: 'https://github.com/backstage/foobar'\n * })\n *\n * const { token, headers } = await getCredentials({\n * url: 'https://github.com/backstage'\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 if (this.#connections) {\n // Ask the connections service to select auth for this URL. A host may\n // have different GitHub Apps for different organizations, so this\n // selection cannot be done once when the provider is created.\n\n const connection = await this.#connections\n .find({\n type: 'github',\n query: { url: opts.url },\n authMethods: ['app', 'token', 'none'],\n })\n .catch(error => {\n throw new ForwardedError(\n 'Failed getting credentials from connection',\n error,\n );\n });\n\n const { auth } = connection;\n\n // Adapt the connection schema to the existing provider configuration so\n // credential creation and token caching stay in one implementation.\n const config: GithubIntegrationConfig = {\n host: connection.host,\n apiBaseUrl: connection.apiBaseUrl,\n rawBaseUrl: connection.rawBaseUrl,\n };\n\n // Reusing an App provider preserves its installation-token cache. App\n // organizations are canonicalized because GitHub owner matching is\n // case-insensitive and does not depend on ordering. Static token\n // providers have no internal token cache, so they are recreated rather\n // than placing their secret token in a cache key.\n let providerKey: string | undefined;\n if (auth.method === 'app') {\n const appId = Number(auth.appId);\n if (!Number.isSafeInteger(appId) || appId <= 0) {\n throw new InputError(\n `Invalid GitHub App ID \"${auth.appId}\", expected a positive safe integer`,\n );\n }\n const normalizedOrgs = auth.orgs?.length\n ? Array.from(new Set(auth.orgs.map(org => org.toLowerCase()))).sort()\n : undefined;\n config.apps = [\n {\n appId,\n privateKey: auth.privateKey,\n clientId: auth.clientId,\n clientSecret: auth.clientSecret,\n webhookSecret: auth.webhookSecret,\n publicAccess: auth.publicAccess,\n allowedInstallationOwners: normalizedOrgs,\n },\n ];\n providerKey = `${connection.host}:app:${appId}:${JSON.stringify(\n normalizedOrgs ?? [],\n )}:${String(auth.publicAccess ?? false)}`;\n } else if (auth.method === 'token') {\n config.token = auth.token;\n } else {\n providerKey = `${connection.host}:none`;\n }\n\n let provider = providerKey ? this.providers.get(providerKey) : undefined;\n if (!provider) {\n provider = SingleInstanceGithubCredentialsProvider.create(config);\n if (providerKey) {\n this.providers.set(providerKey, provider);\n }\n }\n\n return provider.getCredentials(opts);\n }\n\n const parsed = new URL(opts.url);\n const provider = this.providers.get(parsed.host);\n\n if (!provider) {\n throw new Error(\n `There is no GitHub integration that matches ${opts.url}. Please add a configuration for an integration.`,\n );\n }\n\n return provider.getCredentials(opts);\n }\n}\n"],"names":["provider"],"mappings":";;;AA+BO,MAAM,gCAAA,CAEb;AAAA,EACE,OAAO,iBAAiB,YAAA,EAAsC;AAC5D,IAAA,MAAM,oBAAA,uBACA,GAAA,EAAuC;AAE7C,IAAA,YAAA,CAAa,MAAA,CAAO,IAAA,EAAK,CAAE,OAAA,CAAQ,CAAA,WAAA,KAAe;AAChD,MAAA,MAAM,mBAAA,GACJ,uCAAA,CAAwC,MAAA,CAAO,WAAA,CAAY,MAAM,CAAA;AACnE,MAAA,oBAAA,CAAqB,GAAA,CAAI,WAAA,CAAY,MAAA,CAAO,IAAA,EAAM,mBAAmB,CAAA;AAAA,IACvE,CAAC,CAAA;AACD,IAAA,OAAO,IAAI,iCAAiC,oBAAoB,CAAA;AAAA,EAClE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,OAAO,4BAA4B,WAAA,EAAiC;AAClE,IAAA,OAAO,IAAI,gCAAA;AAAA,0BACL,GAAA,EAAuC;AAAA,MAC3C;AAAA,KACF;AAAA,EACF;AAAA,EAEiB,SAAA;AAA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,EAAaA,SAAQ,CAAA;AAAA,QAC1C;AAAA,MACF;AAEA,MAAA,OAAOA,SAAAA,CAAS,eAAe,IAAI,CAAA;AAAA,IACrC;AAEA,IAAA,MAAM,MAAA,GAAS,IAAI,GAAA,CAAI,IAAA,CAAK,GAAG,CAAA;AAC/B,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,SAAA,CAAU,GAAA,CAAI,OAAO,IAAI,CAAA;AAE/C,IAAA,IAAI,CAAC,QAAA,EAAU;AACb,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,CAAA,4CAAA,EAA+C,KAAK,GAAG,CAAA,gDAAA;AAAA,OACzD;AAAA,IACF;AAEA,IAAA,OAAO,QAAA,CAAS,eAAe,IAAI,CAAA;AAAA,EACrC;AACF
|
|
1
|
+
{"version":3,"file":"DefaultGithubCredentialsProvider.esm.js","sources":["../../src/github/DefaultGithubCredentialsProvider.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 { GithubCredentials, GithubCredentialsProvider } from './types';\nimport { ScmIntegrationRegistry } from '../registry';\nimport { SingleInstanceGithubCredentialsProvider } from './SingleInstanceGithubCredentialsProvider';\nimport type { ConnectionsService } from '@backstage/connections';\nimport { ForwardedError, InputError } from '@backstage/errors';\nimport type { GithubIntegrationConfig } from './config';\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 DefaultGithubCredentialsProvider\n implements GithubCredentialsProvider\n{\n static fromIntegrations(integrations: ScmIntegrationRegistry) {\n const credentialsProviders: Map<string, GithubCredentialsProvider> =\n new Map<string, GithubCredentialsProvider>();\n\n integrations.github.list().forEach(integration => {\n const credentialsProvider =\n SingleInstanceGithubCredentialsProvider.create(integration.config);\n credentialsProviders.set(integration.config.host, credentialsProvider);\n });\n return new DefaultGithubCredentialsProvider(credentialsProviders);\n }\n\n /**\n * Creates a credentials provider backed by the connections service.\n *\n * @param connections - The connections service used to resolve GitHub credentials.\n * @internal\n */\n static experimentalFromConnections(connections: ConnectionsService) {\n return new DefaultGithubCredentialsProvider(\n new Map<string, GithubCredentialsProvider>(),\n connections,\n );\n }\n\n private readonly providers: Map<string, GithubCredentialsProvider>;\n readonly #connections?: ConnectionsService;\n\n private constructor(\n providers: Map<string, GithubCredentialsProvider>,\n connections?: ConnectionsService,\n ) {\n this.providers = providers;\n this.#connections = connections;\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: 'https://github.com/backstage/foobar'\n * })\n *\n * const { token, headers } = await getCredentials({\n * url: 'https://github.com/backstage'\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 if (this.#connections) {\n // Ask the connections service to select auth for this URL. A host may\n // have different GitHub Apps for different organizations, so this\n // selection cannot be done once when the provider is created.\n\n const connection = await this.#connections\n .find({\n type: 'github',\n query: { url: opts.url },\n authMethods: ['app', 'token', 'none'],\n })\n .catch(error => {\n throw new ForwardedError(\n 'Failed getting credentials from connection',\n error,\n );\n });\n\n const { auth } = connection;\n\n // Adapt the connection schema to the existing provider configuration so\n // credential creation and token caching stay in one implementation.\n const config: GithubIntegrationConfig = {\n host: connection.host,\n apiBaseUrl: connection.apiBaseUrl,\n rawBaseUrl: connection.rawBaseUrl,\n };\n\n // Reusing an App provider preserves its installation-token cache. App\n // organizations are canonicalized because GitHub owner matching is\n // case-insensitive and does not depend on ordering. Static token\n // providers have no internal token cache, so they are recreated rather\n // than placing their secret token in a cache key.\n let providerKey: string | undefined;\n if (auth.method === 'app') {\n const appId = Number(auth.appId);\n if (!Number.isSafeInteger(appId) || appId <= 0) {\n throw new InputError(\n `Invalid GitHub App ID \"${auth.appId}\", expected a positive safe integer`,\n );\n }\n const normalizedOrgs = auth.orgs?.length\n ? Array.from(new Set(auth.orgs.map(org => org.toLowerCase()))).sort()\n : undefined;\n config.apps = [\n {\n appId,\n privateKey: auth.privateKey,\n clientId: auth.clientId,\n clientSecret: auth.clientSecret,\n webhookSecret: auth.webhookSecret,\n publicAccess: auth.publicAccess,\n allowedInstallationOwners: normalizedOrgs,\n },\n ];\n providerKey = `${connection.host}:app:${appId}:${JSON.stringify(\n normalizedOrgs ?? [],\n )}:${String(auth.publicAccess ?? false)}`;\n } else if (auth.method === 'token') {\n config.token = auth.token;\n } else {\n providerKey = `${connection.host}:none`;\n }\n\n let provider = providerKey ? this.providers.get(providerKey) : undefined;\n if (!provider) {\n provider = SingleInstanceGithubCredentialsProvider.create(config);\n if (providerKey) {\n this.providers.set(providerKey, provider);\n }\n }\n\n return provider.getCredentials(opts);\n }\n\n const parsed = new URL(opts.url);\n const provider = this.providers.get(parsed.host);\n\n if (!provider) {\n throw new Error(\n `There is no GitHub integration that matches ${opts.url}. Please add a configuration for an integration.`,\n );\n }\n\n return provider.getCredentials(opts);\n }\n}\n"],"names":["provider"],"mappings":";;;AA+BO,MAAM,gCAAA,CAEb;AAAA,EACE,OAAO,iBAAiB,YAAA,EAAsC;AAC5D,IAAA,MAAM,oBAAA,uBACA,GAAA,EAAuC;AAE7C,IAAA,YAAA,CAAa,MAAA,CAAO,IAAA,EAAK,CAAE,OAAA,CAAQ,CAAA,WAAA,KAAe;AAChD,MAAA,MAAM,mBAAA,GACJ,uCAAA,CAAwC,MAAA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AK,KAAA;AAAA,MACtB,CAAA,MAAO;AACL,QAAA,WAAA,GAAc,CAAA,EAAG,WAAW,IAAI,CAAA,KAAA,CAAA;AAAA,MAClC;AAEA,MAAA,IAAIA,YAAW,WAAA,GAAc,IAAA,CAAK,SAAA,CAAU,GAAA,CAAI,WAAW,CAAA,GAAI,MAAA;AAC/D,MAAA,IAAI,CAACA,SAAAA,EAAU;AACb,QAAAA,SAAAA,GAAW,uCAAA,CAAwC,MAAA,CAAO,MAAM,CAAA;AAChE,QAAA,IAAI,WAAA,EAAa;AACf,UAAA,IAAA,CAAK,SAAA,CAAU,GAAA,CAAI,WAAA,EAAaA,SAAQ,CAAA;AAAA,QAC1C;AAAA,MACF;AAEA,MAAA,OAAOA,SAAAA,CAAS,eAAe,IAAI,CAAA;AAAA,IACrC;AAEA,IAAA,MAAM,MAAA,GAAS,IAAI,GAAA,CAAI,IAAA,CAAK,GAAG,CAAA;AAC/B,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,SAAA,CAAU,GAAA,CAAI,OAAO,IAAI,CAAA;AAE/C,IAAA,IAAI,CAAC,QAAA,EAAU;AACb,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,CAAA,4CAAA,EAA+C,KAAK,GAAG,CAAA,gDAAA;AAAA,OACzD;AAAA,IACF;AAEA,IAAA,OAAO,QAAA,CAAS,eAAe,IAAI,CAAA;AAAA,EACrC;AACF;;"}
|
|
@@ -7,6 +7,7 @@ class GithubIntegration {
|
|
|
7
7
|
constructor(integrationConfig) {
|
|
8
8
|
this.integrationConfig = integrationConfig;
|
|
9
9
|
}
|
|
10
|
+
integrationConfig;
|
|
10
11
|
static factory = ({ config: config$1 }) => {
|
|
11
12
|
const configs = config.readGithubIntegrationConfigs(
|
|
12
13
|
config$1.getOptionalConfigArray("integrations.github") ?? []
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"GithubIntegration.cjs.js","sources":["../../src/github/GithubIntegration.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 { basicIntegrations, defaultScmResolveUrl } from '../helpers';\nimport {\n RateLimitInfo,\n ScmIntegration,\n ScmIntegrationsFactory,\n} from '../types';\nimport {\n GithubIntegrationConfig,\n readGithubIntegrationConfigs,\n} from './config';\nimport { ConsumedResponse } from '@backstage/errors';\n\n/**\n * A GitHub based integration.\n *\n * @public\n */\nexport class GithubIntegration implements ScmIntegration {\n static factory: ScmIntegrationsFactory<GithubIntegration> = ({ config }) => {\n const configs = readGithubIntegrationConfigs(\n config.getOptionalConfigArray('integrations.github') ?? [],\n );\n return basicIntegrations(\n configs.map(c => new GithubIntegration(c)),\n i => i.config.host,\n );\n };\n\n constructor(private readonly integrationConfig: GithubIntegrationConfig) {}\n\n get type(): string {\n return 'github';\n }\n\n get title(): string {\n return this.integrationConfig.host;\n }\n\n get config(): GithubIntegrationConfig {\n return this.integrationConfig;\n }\n\n resolveUrl(options: {\n url: string;\n base: string;\n lineNumber?: number;\n }): string {\n // GitHub uses blob URLs for files and tree urls for directory listings. But\n // there is a redirect from tree to blob for files, so we can always return\n // tree urls here.\n return replaceGithubUrlType(defaultScmResolveUrl(options), 'tree');\n }\n\n resolveEditUrl(url: string): string {\n return replaceGithubUrlType(url, 'edit');\n }\n\n parseRateLimitInfo(response: ConsumedResponse): RateLimitInfo {\n return {\n isRateLimited:\n response.status === 429 ||\n (response.status === 403 &&\n response.headers.get('x-ratelimit-remaining') === '0'),\n };\n }\n}\n\n/**\n * Takes a GitHub URL and replaces the type part (blob, tree etc).\n *\n * @param url - The original URL\n * @param type - The desired type, e.g. \"blob\"\n * @public\n */\nexport function replaceGithubUrlType(\n url: string,\n type: 'blob' | 'tree' | 'edit',\n): string {\n return url.replace(\n /\\/\\/([^/]+)\\/([^/]+)\\/([^/]+)\\/(blob|tree|edit)\\//,\n (_, host, owner, repo) => {\n return `//${host}/${owner}/${repo}/${type}/`;\n },\n );\n}\n"],"names":["config","readGithubIntegrationConfigs","basicIntegrations","defaultScmResolveUrl"],"mappings":";;;;;AAiCO,MAAM,iBAAA,CAA4C;AAAA,EAWvD,YAA6B,iBAAA,EAA4C;AAA5C,IAAA,IAAA,CAAA,iBAAA,GAAA,iBAAA;AAAA,EAA6C;AAAA,
|
|
1
|
+
{"version":3,"file":"GithubIntegration.cjs.js","sources":["../../src/github/GithubIntegration.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 { basicIntegrations, defaultScmResolveUrl } from '../helpers';\nimport {\n RateLimitInfo,\n ScmIntegration,\n ScmIntegrationsFactory,\n} from '../types';\nimport {\n GithubIntegrationConfig,\n readGithubIntegrationConfigs,\n} from './config';\nimport { ConsumedResponse } from '@backstage/errors';\n\n/**\n * A GitHub based integration.\n *\n * @public\n */\nexport class GithubIntegration implements ScmIntegration {\n static factory: ScmIntegrationsFactory<GithubIntegration> = ({ config }) => {\n const configs = readGithubIntegrationConfigs(\n config.getOptionalConfigArray('integrations.github') ?? [],\n );\n return basicIntegrations(\n configs.map(c => new GithubIntegration(c)),\n i => i.config.host,\n );\n };\n\n constructor(private readonly integrationConfig: GithubIntegrationConfig) {}\n\n get type(): string {\n return 'github';\n }\n\n get title(): string {\n return this.integrationConfig.host;\n }\n\n get config(): GithubIntegrationConfig {\n return this.integrationConfig;\n }\n\n resolveUrl(options: {\n url: string;\n base: string;\n lineNumber?: number;\n }): string {\n // GitHub uses blob URLs for files and tree urls for directory listings. But\n // there is a redirect from tree to blob for files, so we can always return\n // tree urls here.\n return replaceGithubUrlType(defaultScmResolveUrl(options), 'tree');\n }\n\n resolveEditUrl(url: string): string {\n return replaceGithubUrlType(url, 'edit');\n }\n\n parseRateLimitInfo(response: ConsumedResponse): RateLimitInfo {\n return {\n isRateLimited:\n response.status === 429 ||\n (response.status === 403 &&\n response.headers.get('x-ratelimit-remaining') === '0'),\n };\n }\n}\n\n/**\n * Takes a GitHub URL and replaces the type part (blob, tree etc).\n *\n * @param url - The original URL\n * @param type - The desired type, e.g. \"blob\"\n * @public\n */\nexport function replaceGithubUrlType(\n url: string,\n type: 'blob' | 'tree' | 'edit',\n): string {\n return url.replace(\n /\\/\\/([^/]+)\\/([^/]+)\\/([^/]+)\\/(blob|tree|edit)\\//,\n (_, host, owner, repo) => {\n return `//${host}/${owner}/${repo}/${type}/`;\n },\n );\n}\n"],"names":["config","readGithubIntegrationConfigs","basicIntegrations","defaultScmResolveUrl"],"mappings":";;;;;AAiCO,MAAM,iBAAA,CAA4C;AAAA,EAWvD,YAA6B,iBAAA,EAA4C;AAA5C,IAAA,IAAA,CAAA,iBAAA,GAAA,iBAAA;AAAA,EAA6C;AAAA,EAA7C,iBAAA;AAAA,EAV7B,OAAO,OAAA,GAAqD,CAAC,UAAEA,UAAO,KAAM;AAC1E,IAAA,MAAM,OAAA,GAAUC,mCAAA;AAAA,MACdD,QAAA,CAAO,sBAAA,CAAuB,qBAAqB,CAAA,IAAK;AAAC,KAC3D;AACA,IAAA,OAAOE,yBAAA;AAAA,MACL,QAAQ,GAAA,CAAI,CAAA,CAAA,KAAK,IAAI,iBAAA,CAAkB,CAAC,CAAC,CAAA;AAAA,MACzC,CAAA,CAAA,KAAK,EAAE,MAAA,CAAO;AAAA,KAChB;AAAA,EACF,CAAA;AAAA,EAIA,IAAI,IAAA,GAAe;AACjB,IAAA,OAAO,QAAA;AAAA,EACT;AAAA,EAEA,IAAI,KAAA,GAAgB;AAClB,IAAA,OAAO,KAAK,iBAAA,CAAkB,IAAA;AAAA,EAChC;AAAA,EAEA,IAAI,MAAA,GAAkC;AACpC,IAAA,OAAO,IAAA,CAAK,iBAAA;AAAA,EACd;AAAA,EAEA,WAAW,OAAA,EAIA;AAIT,IAAA,OAAO,oBAAA,CAAqBC,4BAAA,CAAqB,OAAO,CAAA,EAAG,MAAM,CAAA;AAAA,EACnE;AAAA,EAEA,eAAe,GAAA,EAAqB;AAClC,IAAA,OAAO,oBAAA,CAAqB,KAAK,MAAM,CAAA;AAAA,EACzC;AAAA,EAEA,mBAAmB,QAAA,EAA2C;AAC5D,IAAA,OAAO;AAAA,MACL,aAAA,EACE,QAAA,CAAS,MAAA,KAAW,GAAA,IACnB,QAAA,CAAS,MAAA,KAAW,GAAA,IACnB,QAAA,CAAS,OAAA,CAAQ,GAAA,CAAI,uBAAuB,CAAA,KAAM;AAAA,KACxD;AAAA,EACF;AACF;AASO,SAAS,oBAAA,CACd,KACA,IAAA,EACQ;AACR,EAAA,OAAO,GAAA,CAAI,OAAA;AAAA,IACT,mDAAA;AAAA,IACA,CAAC,CAAA,EAAG,IAAA,EAAM,KAAA,EAAO,IAAA,KAAS;AACxB,MAAA,OAAO,KAAK,IAAI,CAAA,CAAA,EAAI,KAAK,CAAA,CAAA,EAAI,IAAI,IAAI,IAAI,CAAA,CAAA,CAAA;AAAA,IAC3C;AAAA,GACF;AACF;;;"}
|
|
@@ -5,6 +5,7 @@ class GithubIntegration {
|
|
|
5
5
|
constructor(integrationConfig) {
|
|
6
6
|
this.integrationConfig = integrationConfig;
|
|
7
7
|
}
|
|
8
|
+
integrationConfig;
|
|
8
9
|
static factory = ({ config }) => {
|
|
9
10
|
const configs = readGithubIntegrationConfigs(
|
|
10
11
|
config.getOptionalConfigArray("integrations.github") ?? []
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"GithubIntegration.esm.js","sources":["../../src/github/GithubIntegration.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 { basicIntegrations, defaultScmResolveUrl } from '../helpers';\nimport {\n RateLimitInfo,\n ScmIntegration,\n ScmIntegrationsFactory,\n} from '../types';\nimport {\n GithubIntegrationConfig,\n readGithubIntegrationConfigs,\n} from './config';\nimport { ConsumedResponse } from '@backstage/errors';\n\n/**\n * A GitHub based integration.\n *\n * @public\n */\nexport class GithubIntegration implements ScmIntegration {\n static factory: ScmIntegrationsFactory<GithubIntegration> = ({ config }) => {\n const configs = readGithubIntegrationConfigs(\n config.getOptionalConfigArray('integrations.github') ?? [],\n );\n return basicIntegrations(\n configs.map(c => new GithubIntegration(c)),\n i => i.config.host,\n );\n };\n\n constructor(private readonly integrationConfig: GithubIntegrationConfig) {}\n\n get type(): string {\n return 'github';\n }\n\n get title(): string {\n return this.integrationConfig.host;\n }\n\n get config(): GithubIntegrationConfig {\n return this.integrationConfig;\n }\n\n resolveUrl(options: {\n url: string;\n base: string;\n lineNumber?: number;\n }): string {\n // GitHub uses blob URLs for files and tree urls for directory listings. But\n // there is a redirect from tree to blob for files, so we can always return\n // tree urls here.\n return replaceGithubUrlType(defaultScmResolveUrl(options), 'tree');\n }\n\n resolveEditUrl(url: string): string {\n return replaceGithubUrlType(url, 'edit');\n }\n\n parseRateLimitInfo(response: ConsumedResponse): RateLimitInfo {\n return {\n isRateLimited:\n response.status === 429 ||\n (response.status === 403 &&\n response.headers.get('x-ratelimit-remaining') === '0'),\n };\n }\n}\n\n/**\n * Takes a GitHub URL and replaces the type part (blob, tree etc).\n *\n * @param url - The original URL\n * @param type - The desired type, e.g. \"blob\"\n * @public\n */\nexport function replaceGithubUrlType(\n url: string,\n type: 'blob' | 'tree' | 'edit',\n): string {\n return url.replace(\n /\\/\\/([^/]+)\\/([^/]+)\\/([^/]+)\\/(blob|tree|edit)\\//,\n (_, host, owner, repo) => {\n return `//${host}/${owner}/${repo}/${type}/`;\n },\n );\n}\n"],"names":[],"mappings":";;;AAiCO,MAAM,iBAAA,CAA4C;AAAA,EAWvD,YAA6B,iBAAA,EAA4C;AAA5C,IAAA,IAAA,CAAA,iBAAA,GAAA,iBAAA;AAAA,EAA6C;AAAA,
|
|
1
|
+
{"version":3,"file":"GithubIntegration.esm.js","sources":["../../src/github/GithubIntegration.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 { basicIntegrations, defaultScmResolveUrl } from '../helpers';\nimport {\n RateLimitInfo,\n ScmIntegration,\n ScmIntegrationsFactory,\n} from '../types';\nimport {\n GithubIntegrationConfig,\n readGithubIntegrationConfigs,\n} from './config';\nimport { ConsumedResponse } from '@backstage/errors';\n\n/**\n * A GitHub based integration.\n *\n * @public\n */\nexport class GithubIntegration implements ScmIntegration {\n static factory: ScmIntegrationsFactory<GithubIntegration> = ({ config }) => {\n const configs = readGithubIntegrationConfigs(\n config.getOptionalConfigArray('integrations.github') ?? [],\n );\n return basicIntegrations(\n configs.map(c => new GithubIntegration(c)),\n i => i.config.host,\n );\n };\n\n constructor(private readonly integrationConfig: GithubIntegrationConfig) {}\n\n get type(): string {\n return 'github';\n }\n\n get title(): string {\n return this.integrationConfig.host;\n }\n\n get config(): GithubIntegrationConfig {\n return this.integrationConfig;\n }\n\n resolveUrl(options: {\n url: string;\n base: string;\n lineNumber?: number;\n }): string {\n // GitHub uses blob URLs for files and tree urls for directory listings. But\n // there is a redirect from tree to blob for files, so we can always return\n // tree urls here.\n return replaceGithubUrlType(defaultScmResolveUrl(options), 'tree');\n }\n\n resolveEditUrl(url: string): string {\n return replaceGithubUrlType(url, 'edit');\n }\n\n parseRateLimitInfo(response: ConsumedResponse): RateLimitInfo {\n return {\n isRateLimited:\n response.status === 429 ||\n (response.status === 403 &&\n response.headers.get('x-ratelimit-remaining') === '0'),\n };\n }\n}\n\n/**\n * Takes a GitHub URL and replaces the type part (blob, tree etc).\n *\n * @param url - The original URL\n * @param type - The desired type, e.g. \"blob\"\n * @public\n */\nexport function replaceGithubUrlType(\n url: string,\n type: 'blob' | 'tree' | 'edit',\n): string {\n return url.replace(\n /\\/\\/([^/]+)\\/([^/]+)\\/([^/]+)\\/(blob|tree|edit)\\//,\n (_, host, owner, repo) => {\n return `//${host}/${owner}/${repo}/${type}/`;\n },\n );\n}\n"],"names":[],"mappings":";;;AAiCO,MAAM,iBAAA,CAA4C;AAAA,EAWvD,YAA6B,iBAAA,EAA4C;AAA5C,IAAA,IAAA,CAAA,iBAAA,GAAA,iBAAA;AAAA,EAA6C;AAAA,EAA7C,iBAAA;AAAA,EAV7B,OAAO,OAAA,GAAqD,CAAC,EAAE,QAAO,KAAM;AAC1E,IAAA,MAAM,OAAA,GAAU,4BAAA;AAAA,MACd,MAAA,CAAO,sBAAA,CAAuB,qBAAqB,CAAA,IAAK;AAAC,KAC3D;AACA,IAAA,OAAO,iBAAA;AAAA,MACL,QAAQ,GAAA,CAAI,CAAA,CAAA,KAAK,IAAI,iBAAA,CAAkB,CAAC,CAAC,CAAA;AAAA,MACzC,CAAA,CAAA,KAAK,EAAE,MAAA,CAAO;AAAA,KAChB;AAAA,EACF,CAAA;AAAA,EAIA,IAAI,IAAA,GAAe;AACjB,IAAA,OAAO,QAAA;AAAA,EACT;AAAA,EAEA,IAAI,KAAA,GAAgB;AAClB,IAAA,OAAO,KAAK,iBAAA,CAAkB,IAAA;AAAA,EAChC;AAAA,EAEA,IAAI,MAAA,GAAkC;AACpC,IAAA,OAAO,IAAA,CAAK,iBAAA;AAAA,EACd;AAAA,EAEA,WAAW,OAAA,EAIA;AAIT,IAAA,OAAO,oBAAA,CAAqB,oBAAA,CAAqB,OAAO,CAAA,EAAG,MAAM,CAAA;AAAA,EACnE;AAAA,EAEA,eAAe,GAAA,EAAqB;AAClC,IAAA,OAAO,oBAAA,CAAqB,KAAK,MAAM,CAAA;AAAA,EACzC;AAAA,EAEA,mBAAmB,QAAA,EAA2C;AAC5D,IAAA,OAAO;AAAA,MACL,aAAA,EACE,QAAA,CAAS,MAAA,KAAW,GAAA,IACnB,QAAA,CAAS,MAAA,KAAW,GAAA,IACnB,QAAA,CAAS,OAAA,CAAQ,GAAA,CAAI,uBAAuB,CAAA,KAAM;AAAA,KACxD;AAAA,EACF;AACF;AASO,SAAS,oBAAA,CACd,KACA,IAAA,EACQ;AACR,EAAA,OAAO,GAAA,CAAI,OAAA;AAAA,IACT,mDAAA;AAAA,IACA,CAAC,CAAA,EAAG,IAAA,EAAM,KAAA,EAAO,IAAA,KAAS;AACxB,MAAA,OAAO,KAAK,IAAI,CAAA,CAAA,EAAI,KAAK,CAAA,CAAA,EAAI,IAAI,IAAI,IAAI,CAAA,CAAA,CAAA;AAAA,IAC3C;AAAA,GACF;AACF;;"}
|
|
@@ -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 { cloneDeep } from 'lodash';\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\ntype Installations =\n RestEndpointMethodTypes['apps']['listInstallations']['response']['data'];\n\n// How long a listInstallations response may be reused before refetching.\n// Short enough that newly-added installations show up quickly, long enough\n// that token refresh cycles don't re-paginate on every miss.\nconst INSTALLATIONS_CACHE_TTL_MINUTES = 10;\n\n// Minimum time between on-demand refreshes triggered by an owner miss. This\n// keeps the cache from being paginated on every lookup for an unknown owner,\n// while still letting a newly-added installation show up before the TTL.\nconst INSTALLATIONS_REFRESH_THROTTLE_SECONDS = 60;\n\nfunction isStaleInstallationError(error: unknown): boolean {\n if (typeof error !== 'object' || error === null) {\n return false;\n }\n const status = (error as { status?: unknown }).status;\n return status === 404 || status === 410;\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 private installationsCache?: {\n data: Installations;\n fetchedAt: DateTime;\n expiresAt: DateTime;\n };\n private lastInstallationsRefreshAttempt?: DateTime;\n private pendingInstallations?: Promise<Installations>;\n public readonly publicAccess: boolean;\n\n constructor(config: GithubAppConfig, baseUrl?: string) {\n this.allowedInstallationOwners = config.allowedInstallationOwners?.map(\n owner => owner.toLowerCase(),\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 this.publicAccess = config.publicAccess ?? false;\n }\n\n async getInstallationCredentials(\n owner?: string,\n repo?: string,\n ): Promise<{ accessToken: string | undefined }> {\n // No owner means a bare host URL (e.g. https://github.com) — return an\n // app-level JWT rather than an installation token.\n if (!owner) {\n const auth = createAppAuth({\n appId: this.baseAuthConfig.appId,\n privateKey: this.baseAuthConfig.privateKey,\n });\n const { token } = await auth({ type: 'app' });\n return { accessToken: token };\n }\n\n if (this.allowedInstallationOwners) {\n if (!this.allowedInstallationOwners?.includes(owner.toLowerCase())) {\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.createInstallationAccessToken(installationId);\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 async getPublicInstallationToken(): Promise<{ accessToken: string }> {\n const [installation] = await this.getCachedInstallations();\n\n if (!installation) {\n throw new Error(`No installation found for public app`);\n }\n\n return this.cache.getOrCreateToken(\n `public:${installation.id}`,\n undefined,\n async () => {\n const result = await this.createInstallationAccessToken(\n installation.id,\n );\n\n return {\n token: result.data.token,\n expiresAt: DateTime.fromISO(result.data.expires_at),\n };\n },\n );\n }\n\n private async createInstallationAccessToken(installationId: number) {\n try {\n return await this.appClient.apps.createInstallationAccessToken({\n installation_id: installationId,\n headers: HEADERS,\n });\n } catch (error) {\n // A 404/410 means the installation referenced in our cache no longer\n // exists, so drop the cache to force a refresh on the next lookup.\n if (isStaleInstallationError(error)) {\n this.installationsCache = undefined;\n }\n throw error;\n }\n }\n\n async getInstallations(): Promise<Installations> {\n return cloneDeep(await this.getCachedInstallations());\n }\n\n private async getCachedInstallations(\n options: { forceRefresh?: boolean } = {},\n ): Promise<Installations> {\n if (\n !options.forceRefresh &&\n this.installationsCache &&\n DateTime.local() < this.installationsCache.expiresAt\n ) {\n return this.installationsCache.data;\n }\n if (!this.pendingInstallations) {\n const pending = this.appClient\n .paginate(this.appClient.apps.listInstallations)\n .then(data => {\n const now = DateTime.local();\n this.installationsCache = {\n data,\n fetchedAt: now,\n expiresAt: now.plus({ minutes: INSTALLATIONS_CACHE_TTL_MINUTES }),\n };\n return data;\n })\n .finally(() => {\n this.lastInstallationsRefreshAttempt = DateTime.local();\n if (this.pendingInstallations === pending) {\n this.pendingInstallations = undefined;\n }\n });\n this.pendingInstallations = pending;\n }\n return await this.pendingInstallations;\n }\n\n private async getInstallationData(owner: string): Promise<InstallationData> {\n const ownerLower = owner.toLowerCase();\n const find = (list: Installations) =>\n list.find(\n inst =>\n inst.account &&\n 'login' in inst.account &&\n inst.account.login?.toLowerCase() === ownerLower,\n );\n\n let installations = await this.getCachedInstallations();\n let installation = find(installations);\n\n // Owner not in cache — a newly-created installation may have appeared\n // since we last paginated. Force a refresh (throttled) before failing.\n if (!installation && this.canRefreshInstallations()) {\n installations = await this.getCachedInstallations({\n forceRefresh: true,\n });\n installation = find(installations);\n }\n\n if (installation) {\n return {\n installationId: installation.id,\n suspended: Boolean(installation.suspended_by),\n };\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 private canRefreshInstallations(): boolean {\n if (!this.installationsCache) {\n return true;\n }\n const refreshReference =\n this.lastInstallationsRefreshAttempt ?? this.installationsCache.fetchedAt;\n const age = DateTime.local().diff(refreshReference).as('seconds');\n return age >= INSTALLATIONS_REFRESH_THROTTLE_SECONDS;\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(\n owner?: string,\n repo?: string,\n ): 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\n if (result) {\n return result.credentials!.accessToken;\n }\n\n // If there was no token returned, then let's find a public access app and use an installation to get a token.\n const publicAccessApp = this.apps.find(app => app.publicAccess);\n if (publicAccessApp) {\n const publicResult = await publicAccessApp\n .getPublicInstallationToken()\n .then(\n credentials => ({ credentials, error: undefined }),\n error => ({ credentials: undefined, error }),\n );\n\n if (publicResult.credentials?.accessToken) {\n return publicResult.credentials.accessToken;\n }\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","cloneDeep","parseGitUrl"],"mappings":";;;;;;;;;;;;AAuCA,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,CAA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A;AAAA;AAAA,EAsBA,MAAM,eAAe,IAAA,EAAmD;AACtE,IAAA,MAAM,MAAA,GAASI,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;;;;;"}
|
|
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 { cloneDeep } from 'lodash';\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\ntype Installations =\n RestEndpointMethodTypes['apps']['listInstallations']['response']['data'];\n\n// How long a listInstallations response may be reused before refetching.\n// Short enough that newly-added installations show up quickly, long enough\n// that token refresh cycles don't re-paginate on every miss.\nconst INSTALLATIONS_CACHE_TTL_MINUTES = 10;\n\n// Minimum time between on-demand refreshes triggered by an owner miss. This\n// keeps the cache from being paginated on every lookup for an unknown owner,\n// while still letting a newly-added installation show up before the TTL.\nconst INSTALLATIONS_REFRESH_THROTTLE_SECONDS = 60;\n\nfunction isStaleInstallationError(error: unknown): boolean {\n if (typeof error !== 'object' || error === null) {\n return false;\n }\n const status = (error as { status?: unknown }).status;\n return status === 404 || status === 410;\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 private installationsCache?: {\n data: Installations;\n fetchedAt: DateTime;\n expiresAt: DateTime;\n };\n private lastInstallationsRefreshAttempt?: DateTime;\n private pendingInstallations?: Promise<Installations>;\n public readonly publicAccess: boolean;\n\n constructor(config: GithubAppConfig, baseUrl?: string) {\n this.allowedInstallationOwners = config.allowedInstallationOwners?.map(\n owner => owner.toLowerCase(),\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 this.publicAccess = config.publicAccess ?? false;\n }\n\n async getInstallationCredentials(\n owner?: string,\n repo?: string,\n ): Promise<{ accessToken: string | undefined }> {\n // No owner means a bare host URL (e.g. https://github.com) — return an\n // app-level JWT rather than an installation token.\n if (!owner) {\n const auth = createAppAuth({\n appId: this.baseAuthConfig.appId,\n privateKey: this.baseAuthConfig.privateKey,\n });\n const { token } = await auth({ type: 'app' });\n return { accessToken: token };\n }\n\n if (this.allowedInstallationOwners) {\n if (!this.allowedInstallationOwners?.includes(owner.toLowerCase())) {\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.createInstallationAccessToken(installationId);\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 async getPublicInstallationToken(): Promise<{ accessToken: string }> {\n const [installation] = await this.getCachedInstallations();\n\n if (!installation) {\n throw new Error(`No installation found for public app`);\n }\n\n return this.cache.getOrCreateToken(\n `public:${installation.id}`,\n undefined,\n async () => {\n const result = await this.createInstallationAccessToken(\n installation.id,\n );\n\n return {\n token: result.data.token,\n expiresAt: DateTime.fromISO(result.data.expires_at),\n };\n },\n );\n }\n\n private async createInstallationAccessToken(installationId: number) {\n try {\n return await this.appClient.apps.createInstallationAccessToken({\n installation_id: installationId,\n headers: HEADERS,\n });\n } catch (error) {\n // A 404/410 means the installation referenced in our cache no longer\n // exists, so drop the cache to force a refresh on the next lookup.\n if (isStaleInstallationError(error)) {\n this.installationsCache = undefined;\n }\n throw error;\n }\n }\n\n async getInstallations(): Promise<Installations> {\n return cloneDeep(await this.getCachedInstallations());\n }\n\n private async getCachedInstallations(\n options: { forceRefresh?: boolean } = {},\n ): Promise<Installations> {\n if (\n !options.forceRefresh &&\n this.installationsCache &&\n DateTime.local() < this.installationsCache.expiresAt\n ) {\n return this.installationsCache.data;\n }\n if (!this.pendingInstallations) {\n const pending = this.appClient\n .paginate(this.appClient.apps.listInstallations)\n .then(data => {\n const now = DateTime.local();\n this.installationsCache = {\n data,\n fetchedAt: now,\n expiresAt: now.plus({ minutes: INSTALLATIONS_CACHE_TTL_MINUTES }),\n };\n return data;\n })\n .finally(() => {\n this.lastInstallationsRefreshAttempt = DateTime.local();\n if (this.pendingInstallations === pending) {\n this.pendingInstallations = undefined;\n }\n });\n this.pendingInstallations = pending;\n }\n return await this.pendingInstallations;\n }\n\n private async getInstallationData(owner: string): Promise<InstallationData> {\n const ownerLower = owner.toLowerCase();\n const find = (list: Installations) =>\n list.find(\n inst =>\n inst.account &&\n 'login' in inst.account &&\n inst.account.login?.toLowerCase() === ownerLower,\n );\n\n let installations = await this.getCachedInstallations();\n let installation = find(installations);\n\n // Owner not in cache — a newly-created installation may have appeared\n // since we last paginated. Force a refresh (throttled) before failing.\n if (!installation && this.canRefreshInstallations()) {\n installations = await this.getCachedInstallations({\n forceRefresh: true,\n });\n installation = find(installations);\n }\n\n if (installation) {\n return {\n installationId: installation.id,\n suspended: Boolean(installation.suspended_by),\n };\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 private canRefreshInstallations(): boolean {\n if (!this.installationsCache) {\n return true;\n }\n const refreshReference =\n this.lastInstallationsRefreshAttempt ?? this.installationsCache.fetchedAt;\n const age = DateTime.local().diff(refreshReference).as('seconds');\n return age >= INSTALLATIONS_REFRESH_THROTTLE_SECONDS;\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(\n owner?: string,\n repo?: string,\n ): 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\n if (result) {\n return result.credentials!.accessToken;\n }\n\n // If there was no token returned, then let's find a public access app and use an installation to get a token.\n const publicAccessApp = this.apps.find(app => app.publicAccess);\n if (publicAccessApp) {\n const publicResult = await publicAccessApp\n .getPublicInstallationToken()\n .then(\n credentials => ({ credentials, error: undefined }),\n error => ({ credentials: undefined, error }),\n );\n\n if (publicResult.credentials?.accessToken) {\n return publicResult.credentials.accessToken;\n }\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","cloneDeep","parseGitUrl"],"mappings":";;;;;;;;;;;;AAuCA,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,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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;;;"}
|
|
@@ -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 { cloneDeep } from 'lodash';\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\ntype Installations =\n RestEndpointMethodTypes['apps']['listInstallations']['response']['data'];\n\n// How long a listInstallations response may be reused before refetching.\n// Short enough that newly-added installations show up quickly, long enough\n// that token refresh cycles don't re-paginate on every miss.\nconst INSTALLATIONS_CACHE_TTL_MINUTES = 10;\n\n// Minimum time between on-demand refreshes triggered by an owner miss. This\n// keeps the cache from being paginated on every lookup for an unknown owner,\n// while still letting a newly-added installation show up before the TTL.\nconst INSTALLATIONS_REFRESH_THROTTLE_SECONDS = 60;\n\nfunction isStaleInstallationError(error: unknown): boolean {\n if (typeof error !== 'object' || error === null) {\n return false;\n }\n const status = (error as { status?: unknown }).status;\n return status === 404 || status === 410;\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 private installationsCache?: {\n data: Installations;\n fetchedAt: DateTime;\n expiresAt: DateTime;\n };\n private lastInstallationsRefreshAttempt?: DateTime;\n private pendingInstallations?: Promise<Installations>;\n public readonly publicAccess: boolean;\n\n constructor(config: GithubAppConfig, baseUrl?: string) {\n this.allowedInstallationOwners = config.allowedInstallationOwners?.map(\n owner => owner.toLowerCase(),\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 this.publicAccess = config.publicAccess ?? false;\n }\n\n async getInstallationCredentials(\n owner?: string,\n repo?: string,\n ): Promise<{ accessToken: string | undefined }> {\n // No owner means a bare host URL (e.g. https://github.com) — return an\n // app-level JWT rather than an installation token.\n if (!owner) {\n const auth = createAppAuth({\n appId: this.baseAuthConfig.appId,\n privateKey: this.baseAuthConfig.privateKey,\n });\n const { token } = await auth({ type: 'app' });\n return { accessToken: token };\n }\n\n if (this.allowedInstallationOwners) {\n if (!this.allowedInstallationOwners?.includes(owner.toLowerCase())) {\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.createInstallationAccessToken(installationId);\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 async getPublicInstallationToken(): Promise<{ accessToken: string }> {\n const [installation] = await this.getCachedInstallations();\n\n if (!installation) {\n throw new Error(`No installation found for public app`);\n }\n\n return this.cache.getOrCreateToken(\n `public:${installation.id}`,\n undefined,\n async () => {\n const result = await this.createInstallationAccessToken(\n installation.id,\n );\n\n return {\n token: result.data.token,\n expiresAt: DateTime.fromISO(result.data.expires_at),\n };\n },\n );\n }\n\n private async createInstallationAccessToken(installationId: number) {\n try {\n return await this.appClient.apps.createInstallationAccessToken({\n installation_id: installationId,\n headers: HEADERS,\n });\n } catch (error) {\n // A 404/410 means the installation referenced in our cache no longer\n // exists, so drop the cache to force a refresh on the next lookup.\n if (isStaleInstallationError(error)) {\n this.installationsCache = undefined;\n }\n throw error;\n }\n }\n\n async getInstallations(): Promise<Installations> {\n return cloneDeep(await this.getCachedInstallations());\n }\n\n private async getCachedInstallations(\n options: { forceRefresh?: boolean } = {},\n ): Promise<Installations> {\n if (\n !options.forceRefresh &&\n this.installationsCache &&\n DateTime.local() < this.installationsCache.expiresAt\n ) {\n return this.installationsCache.data;\n }\n if (!this.pendingInstallations) {\n const pending = this.appClient\n .paginate(this.appClient.apps.listInstallations)\n .then(data => {\n const now = DateTime.local();\n this.installationsCache = {\n data,\n fetchedAt: now,\n expiresAt: now.plus({ minutes: INSTALLATIONS_CACHE_TTL_MINUTES }),\n };\n return data;\n })\n .finally(() => {\n this.lastInstallationsRefreshAttempt = DateTime.local();\n if (this.pendingInstallations === pending) {\n this.pendingInstallations = undefined;\n }\n });\n this.pendingInstallations = pending;\n }\n return await this.pendingInstallations;\n }\n\n private async getInstallationData(owner: string): Promise<InstallationData> {\n const ownerLower = owner.toLowerCase();\n const find = (list: Installations) =>\n list.find(\n inst =>\n inst.account &&\n 'login' in inst.account &&\n inst.account.login?.toLowerCase() === ownerLower,\n );\n\n let installations = await this.getCachedInstallations();\n let installation = find(installations);\n\n // Owner not in cache — a newly-created installation may have appeared\n // since we last paginated. Force a refresh (throttled) before failing.\n if (!installation && this.canRefreshInstallations()) {\n installations = await this.getCachedInstallations({\n forceRefresh: true,\n });\n installation = find(installations);\n }\n\n if (installation) {\n return {\n installationId: installation.id,\n suspended: Boolean(installation.suspended_by),\n };\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 private canRefreshInstallations(): boolean {\n if (!this.installationsCache) {\n return true;\n }\n const refreshReference =\n this.lastInstallationsRefreshAttempt ?? this.installationsCache.fetchedAt;\n const age = DateTime.local().diff(refreshReference).as('seconds');\n return age >= INSTALLATIONS_REFRESH_THROTTLE_SECONDS;\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(\n owner?: string,\n repo?: string,\n ): 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\n if (result) {\n return result.credentials!.accessToken;\n }\n\n // If there was no token returned, then let's find a public access app and use an installation to get a token.\n const publicAccessApp = this.apps.find(app => app.publicAccess);\n if (publicAccessApp) {\n const publicResult = await publicAccessApp\n .getPublicInstallationToken()\n .then(\n credentials => ({ credentials, error: undefined }),\n error => ({ credentials: undefined, error }),\n );\n\n if (publicResult.credentials?.accessToken) {\n return publicResult.credentials.accessToken;\n }\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 ?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A,MAAA,KAAU;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,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;;;;"}
|
|
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 { cloneDeep } from 'lodash';\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\ntype Installations =\n RestEndpointMethodTypes['apps']['listInstallations']['response']['data'];\n\n// How long a listInstallations response may be reused before refetching.\n// Short enough that newly-added installations show up quickly, long enough\n// that token refresh cycles don't re-paginate on every miss.\nconst INSTALLATIONS_CACHE_TTL_MINUTES = 10;\n\n// Minimum time between on-demand refreshes triggered by an owner miss. This\n// keeps the cache from being paginated on every lookup for an unknown owner,\n// while still letting a newly-added installation show up before the TTL.\nconst INSTALLATIONS_REFRESH_THROTTLE_SECONDS = 60;\n\nfunction isStaleInstallationError(error: unknown): boolean {\n if (typeof error !== 'object' || error === null) {\n return false;\n }\n const status = (error as { status?: unknown }).status;\n return status === 404 || status === 410;\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 private installationsCache?: {\n data: Installations;\n fetchedAt: DateTime;\n expiresAt: DateTime;\n };\n private lastInstallationsRefreshAttempt?: DateTime;\n private pendingInstallations?: Promise<Installations>;\n public readonly publicAccess: boolean;\n\n constructor(config: GithubAppConfig, baseUrl?: string) {\n this.allowedInstallationOwners = config.allowedInstallationOwners?.map(\n owner => owner.toLowerCase(),\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 this.publicAccess = config.publicAccess ?? false;\n }\n\n async getInstallationCredentials(\n owner?: string,\n repo?: string,\n ): Promise<{ accessToken: string | undefined }> {\n // No owner means a bare host URL (e.g. https://github.com) — return an\n // app-level JWT rather than an installation token.\n if (!owner) {\n const auth = createAppAuth({\n appId: this.baseAuthConfig.appId,\n privateKey: this.baseAuthConfig.privateKey,\n });\n const { token } = await auth({ type: 'app' });\n return { accessToken: token };\n }\n\n if (this.allowedInstallationOwners) {\n if (!this.allowedInstallationOwners?.includes(owner.toLowerCase())) {\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.createInstallationAccessToken(installationId);\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 async getPublicInstallationToken(): Promise<{ accessToken: string }> {\n const [installation] = await this.getCachedInstallations();\n\n if (!installation) {\n throw new Error(`No installation found for public app`);\n }\n\n return this.cache.getOrCreateToken(\n `public:${installation.id}`,\n undefined,\n async () => {\n const result = await this.createInstallationAccessToken(\n installation.id,\n );\n\n return {\n token: result.data.token,\n expiresAt: DateTime.fromISO(result.data.expires_at),\n };\n },\n );\n }\n\n private async createInstallationAccessToken(installationId: number) {\n try {\n return await this.appClient.apps.createInstallationAccessToken({\n installation_id: installationId,\n headers: HEADERS,\n });\n } catch (error) {\n // A 404/410 means the installation referenced in our cache no longer\n // exists, so drop the cache to force a refresh on the next lookup.\n if (isStaleInstallationError(error)) {\n this.installationsCache = undefined;\n }\n throw error;\n }\n }\n\n async getInstallations(): Promise<Installations> {\n return cloneDeep(await this.getCachedInstallations());\n }\n\n private async getCachedInstallations(\n options: { forceRefresh?: boolean } = {},\n ): Promise<Installations> {\n if (\n !options.forceRefresh &&\n this.installationsCache &&\n DateTime.local() < this.installationsCache.expiresAt\n ) {\n return this.installationsCache.data;\n }\n if (!this.pendingInstallations) {\n const pending = this.appClient\n .paginate(this.appClient.apps.listInstallations)\n .then(data => {\n const now = DateTime.local();\n this.installationsCache = {\n data,\n fetchedAt: now,\n expiresAt: now.plus({ minutes: INSTALLATIONS_CACHE_TTL_MINUTES }),\n };\n return data;\n })\n .finally(() => {\n this.lastInstallationsRefreshAttempt = DateTime.local();\n if (this.pendingInstallations === pending) {\n this.pendingInstallations = undefined;\n }\n });\n this.pendingInstallations = pending;\n }\n return await this.pendingInstallations;\n }\n\n private async getInstallationData(owner: string): Promise<InstallationData> {\n const ownerLower = owner.toLowerCase();\n const find = (list: Installations) =>\n list.find(\n inst =>\n inst.account &&\n 'login' in inst.account &&\n inst.account.login?.toLowerCase() === ownerLower,\n );\n\n let installations = await this.getCachedInstallations();\n let installation = find(installations);\n\n // Owner not in cache — a newly-created installation may have appeared\n // since we last paginated. Force a refresh (throttled) before failing.\n if (!installation && this.canRefreshInstallations()) {\n installations = await this.getCachedInstallations({\n forceRefresh: true,\n });\n installation = find(installations);\n }\n\n if (installation) {\n return {\n installationId: installation.id,\n suspended: Boolean(installation.suspended_by),\n };\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 private canRefreshInstallations(): boolean {\n if (!this.installationsCache) {\n return true;\n }\n const refreshReference =\n this.lastInstallationsRefreshAttempt ?? this.installationsCache.fetchedAt;\n const age = DateTime.local().diff(refreshReference).as('seconds');\n return age >= INSTALLATIONS_REFRESH_THROTTLE_SECONDS;\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(\n owner?: string,\n repo?: string,\n ): 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\n if (result) {\n return result.credentials!.accessToken;\n }\n\n // If there was no token returned, then let's find a public access app and use an installation to get a token.\n const publicAccessApp = this.apps.find(app => app.publicAccess);\n if (publicAccessApp) {\n const publicResult = await publicAccessApp\n .getPublicInstallationToken()\n .then(\n credentials => ({ credentials, error: undefined }),\n error => ({ credentials: undefined, error }),\n );\n\n if (publicResult.credentials?.accessToken) {\n return publicResult.credentials.accessToken;\n }\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":";;;;;;AAuCA,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,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,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;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.cjs.js","sources":["../../src/github/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';\nimport { trimEnd } from 'lodash';\nimport { isValidHost } from '../helpers';\n\nconst GITHUB_HOST = 'github.com';\nconst GITHUB_API_BASE_URL = 'https://api.github.com';\nconst GITHUB_RAW_BASE_URL = 'https://raw.githubusercontent.com';\n\n/**\n * The configuration parameters for a single GitHub integration.\n *\n * @public\n */\nexport type GithubIntegrationConfig = {\n /**\n * The host of the target that this matches on, e.g. \"github.com\"\n */\n host: string;\n\n /**\n * The base URL of the API of this provider, e.g. \"https://api.github.com\",\n * with no trailing slash.\n *\n * May be omitted specifically for GitHub; then it will be deduced.\n *\n * The API will always be preferred if both its base URL and a token are\n * present.\n */\n apiBaseUrl?: string;\n\n /**\n * The base URL of the raw fetch endpoint of this provider, e.g.\n * \"https://raw.githubusercontent.com\", with no trailing slash.\n *\n * May be omitted specifically for GitHub; then it will be deduced.\n *\n * The API will always be preferred if both its base URL and a token are\n * present.\n */\n rawBaseUrl?: string;\n\n /**\n * The authorization token to use for requests to this provider.\n *\n * If no token is specified, anonymous access is used.\n */\n token?: string;\n\n /**\n * The GitHub Apps configuration to use for requests to this provider.\n *\n * If no apps are specified, token or anonymous is used.\n */\n apps?: GithubAppConfig[];\n};\n\n/**\n * The configuration parameters for authenticating a GitHub Application.\n *\n * @remarks\n *\n * A GitHub Apps configuration can be generated using the `backstage-cli create-github-app` command.\n *\n * @public\n */\nexport type GithubAppConfig = {\n /**\n * Unique app identifier, found at https://github.com/organizations/$org/settings/apps/$AppName\n */\n appId: number;\n /**\n * The private key is used by the GitHub App integration to authenticate the app.\n * A private key can be generated from the app at https://github.com/organizations/$org/settings/apps/$AppName\n */\n privateKey: string;\n /**\n * Webhook secret can be configured at https://github.com/organizations/$org/settings/apps/$AppName\n */\n webhookSecret?: string;\n /**\n * Found at https://github.com/organizations/$org/settings/apps/$AppName\n */\n clientId: string;\n /**\n * Client secrets can be generated at https://github.com/organizations/$org/settings/apps/$AppName\n */\n clientSecret: string;\n /**\n * List of installation owners allowed to be used by this GitHub app. The GitHub UI does not provide a way to list the installations.\n * However you can list the installations with the GitHub API. You can find the list of installations here:\n * https://api.github.com/app/installations\n * The relevant documentation for this is here.\n * https://docs.github.com/en/rest/reference/apps#list-installations-for-the-authenticated-app--code-samples\n */\n allowedInstallationOwners?: string[];\n /**\n * If true, then an installation token will be issued for access when no other token is available.\n */\n publicAccess?: boolean;\n};\n\n/**\n * Reads a single GitHub integration config.\n *\n * @param config - The config object of a single integration\n * @public\n */\nexport function readGithubIntegrationConfig(\n config: Config,\n): GithubIntegrationConfig {\n const host = config.getOptionalString('host') ?? GITHUB_HOST;\n let apiBaseUrl = config.getOptionalString('apiBaseUrl');\n let rawBaseUrl = config.getOptionalString('rawBaseUrl');\n const token = config.getOptionalString('token')?.trim();\n const apps = config.getOptionalConfigArray('apps')?.map(c => ({\n appId: c.getNumber('appId'),\n clientId: c.getString('clientId'),\n clientSecret: c.getString('clientSecret'),\n webhookSecret: c.getOptionalString('webhookSecret'),\n privateKey: c.getString('privateKey'),\n allowedInstallationOwners: c.getOptionalStringArray(\n 'allowedInstallationOwners',\n ),\n publicAccess: c.getOptionalBoolean('publicAccess'),\n }));\n\n if (!isValidHost(host)) {\n throw new Error(\n `Invalid GitHub integration config, '${host}' is not a valid host`,\n );\n }\n\n if (apiBaseUrl) {\n apiBaseUrl = trimEnd(apiBaseUrl, '/');\n } else if (host === GITHUB_HOST) {\n apiBaseUrl = GITHUB_API_BASE_URL;\n }\n\n if (rawBaseUrl) {\n rawBaseUrl = trimEnd(rawBaseUrl, '/');\n } else if (host === GITHUB_HOST) {\n rawBaseUrl = GITHUB_RAW_BASE_URL;\n }\n\n return { host, apiBaseUrl, rawBaseUrl, token, apps };\n}\n\n/**\n * Reads a set of GitHub integration configs, and inserts some defaults for\n * public GitHub if not specified.\n *\n * @param configs - All of the integration config objects\n * @public\n */\nexport function readGithubIntegrationConfigs(\n configs: Config[],\n): GithubIntegrationConfig[] {\n // First read all the explicit integrations\n const result = configs.map(readGithubIntegrationConfig);\n\n // If no explicit github.com integration was added, put one in the list as\n // a convenience\n if (!result.some(c => c.host === GITHUB_HOST)) {\n result.push({\n host: GITHUB_HOST,\n apiBaseUrl: GITHUB_API_BASE_URL,\n rawBaseUrl: GITHUB_RAW_BASE_URL,\n });\n }\n\n return result;\n}\n"],"names":["isValidHost","trimEnd"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CAAA,MAAA,IAAW,SAAS,WAAA,EAAa;AAC/B,IAAA,UAAA,GAAa,mBAAA;AAAA,EACf;AAEA,EAAA,IAAI,UAAA,EAAY;AACd,IAAA,UAAA,GAAaA,cAAA,CAAQ,YAAY,GAAG,CAAA;AAAA,EACtC,CAAA,MAAA,IAAW,SAAS,WAAA,EAAa;AAC/B,IAAA,UAAA,GAAa,mBAAA;AAAA,EACf;AAEA,EAAA,OAAO,EAAE,IAAA,EAAM,UAAA,EAAY,UAAA,EAAY,OAAO,IAAA,EAAK;AACrD;AASO,SAAS,6BACd,OAAA,EAC2B;AAE3B,EAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,GAAA,CAAI,2BAA2B,CAAA;AAItD,EAAA,IAAI,CAAC,MAAA,CAAO,IAAA,CAAK,OAAK,CAAA,CAAE,IAAA,KAAS,WAAW,CAAA,EAAG;AAC7C,IAAA,MAAA,CAAO,IAAA,CAAK;AAAA,MACV,IAAA,EAAM,WAAA;AAAA,MACN,UAAA,EAAY,mBAAA;AAAA,MACZ,UAAA,EAAY;AAAA,KACb,CAAA;AAAA,EACH;AAEA,EAAA,OAAO,MAAA;AACT
|
|
1
|
+
{"version":3,"file":"config.cjs.js","sources":["../../src/github/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';\nimport { trimEnd } from 'lodash';\nimport { isValidHost } from '../helpers';\n\nconst GITHUB_HOST = 'github.com';\nconst GITHUB_API_BASE_URL = 'https://api.github.com';\nconst GITHUB_RAW_BASE_URL = 'https://raw.githubusercontent.com';\n\n/**\n * The configuration parameters for a single GitHub integration.\n *\n * @public\n */\nexport type GithubIntegrationConfig = {\n /**\n * The host of the target that this matches on, e.g. \"github.com\"\n */\n host: string;\n\n /**\n * The base URL of the API of this provider, e.g. \"https://api.github.com\",\n * with no trailing slash.\n *\n * May be omitted specifically for GitHub; then it will be deduced.\n *\n * The API will always be preferred if both its base URL and a token are\n * present.\n */\n apiBaseUrl?: string;\n\n /**\n * The base URL of the raw fetch endpoint of this provider, e.g.\n * \"https://raw.githubusercontent.com\", with no trailing slash.\n *\n * May be omitted specifically for GitHub; then it will be deduced.\n *\n * The API will always be preferred if both its base URL and a token are\n * present.\n */\n rawBaseUrl?: string;\n\n /**\n * The authorization token to use for requests to this provider.\n *\n * If no token is specified, anonymous access is used.\n */\n token?: string;\n\n /**\n * The GitHub Apps configuration to use for requests to this provider.\n *\n * If no apps are specified, token or anonymous is used.\n */\n apps?: GithubAppConfig[];\n};\n\n/**\n * The configuration parameters for authenticating a GitHub Application.\n *\n * @remarks\n *\n * A GitHub Apps configuration can be generated using the `backstage-cli create-github-app` command.\n *\n * @public\n */\nexport type GithubAppConfig = {\n /**\n * Unique app identifier, found at https://github.com/organizations/$org/settings/apps/$AppName\n */\n appId: number;\n /**\n * The private key is used by the GitHub App integration to authenticate the app.\n * A private key can be generated from the app at https://github.com/organizations/$org/settings/apps/$AppName\n */\n privateKey: string;\n /**\n * Webhook secret can be configured at https://github.com/organizations/$org/settings/apps/$AppName\n */\n webhookSecret?: string;\n /**\n * Found at https://github.com/organizations/$org/settings/apps/$AppName\n */\n clientId: string;\n /**\n * Client secrets can be generated at https://github.com/organizations/$org/settings/apps/$AppName\n */\n clientSecret: string;\n /**\n * List of installation owners allowed to be used by this GitHub app. The GitHub UI does not provide a way to list the installations.\n * However you can list the installations with the GitHub API. You can find the list of installations here:\n * https://api.github.com/app/installations\n * The relevant documentation for this is here.\n * https://docs.github.com/en/rest/reference/apps#list-installations-for-the-authenticated-app--code-samples\n */\n allowedInstallationOwners?: string[];\n /**\n * If true, then an installation token will be issued for access when no other token is available.\n */\n publicAccess?: boolean;\n};\n\n/**\n * Reads a single GitHub integration config.\n *\n * @param config - The config object of a single integration\n * @public\n */\nexport function readGithubIntegrationConfig(\n config: Config,\n): GithubIntegrationConfig {\n const host = config.getOptionalString('host') ?? GITHUB_HOST;\n let apiBaseUrl = config.getOptionalString('apiBaseUrl');\n let rawBaseUrl = config.getOptionalString('rawBaseUrl');\n const token = config.getOptionalString('token')?.trim();\n const apps = config.getOptionalConfigArray('apps')?.map(c => ({\n appId: c.getNumber('appId'),\n clientId: c.getString('clientId'),\n clientSecret: c.getString('clientSecret'),\n webhookSecret: c.getOptionalString('webhookSecret'),\n privateKey: c.getString('privateKey'),\n allowedInstallationOwners: c.getOptionalStringArray(\n 'allowedInstallationOwners',\n ),\n publicAccess: c.getOptionalBoolean('publicAccess'),\n }));\n\n if (!isValidHost(host)) {\n throw new Error(\n `Invalid GitHub integration config, '${host}' is not a valid host`,\n );\n }\n\n if (apiBaseUrl) {\n apiBaseUrl = trimEnd(apiBaseUrl, '/');\n } else if (host === GITHUB_HOST) {\n apiBaseUrl = GITHUB_API_BASE_URL;\n }\n\n if (rawBaseUrl) {\n rawBaseUrl = trimEnd(rawBaseUrl, '/');\n } else if (host === GITHUB_HOST) {\n rawBaseUrl = GITHUB_RAW_BASE_URL;\n }\n\n return { host, apiBaseUrl, rawBaseUrl, token, apps };\n}\n\n/**\n * Reads a set of GitHub integration configs, and inserts some defaults for\n * public GitHub if not specified.\n *\n * @param configs - All of the integration config objects\n * @public\n */\nexport function readGithubIntegrationConfigs(\n configs: Config[],\n): GithubIntegrationConfig[] {\n // First read all the explicit integrations\n const result = configs.map(readGithubIntegrationConfig);\n\n // If no explicit github.com integration was added, put one in the list as\n // a convenience\n if (!result.some(c => c.host === GITHUB_HOST)) {\n result.push({\n host: GITHUB_HOST,\n apiBaseUrl: GITHUB_API_BASE_URL,\n rawBaseUrl: GITHUB_RAW_BASE_URL,\n });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A,CAAQ,YAAY,GAAG,CAAA;AAAA,EACtC,CAAA,MAAA,IAAW,SAAS,WAAA,EAAa;AAC/B,IAAA,UAAA,GAAa,mBAAA;AAAA,EACf;AAEA,EAAA,IAAI,UAAA,EAAY;AACd,IAAA,UAAA,GAAaA,cAAA,CAAQ,YAAY,GAAG,CAAA;AAAA,EACtC,CAAA,MAAA,IAAW,SAAS,WAAA,EAAa;AAC/B,IAAA,UAAA,GAAa,mBAAA;AAAA,EACf;AAEA,EAAA,OAAO,EAAE,IAAA,EAAM,UAAA,EAAY,UAAA,EAAY,OAAO,IAAA,EAAK;AACrD;AASO,SAAS,6BACd,OAAA,EAC2B;AAE3B,EAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,GAAA,CAAI,2BAA2B,CAAA;AAItD,EAAA,IAAI,CAAC,MAAA,CAAO,IAAA,CAAK,OAAK,CAAA,CAAE,IAAA,KAAS,WAAW,CAAA,EAAG;AAC7C,IAAA,MAAA,CAAO,IAAA,CAAK;AAAA,MACV,IAAA,EAAM,WAAA;AAAA,MACN,UAAA,EAAY,mBAAA;AAAA,MACZ,UAAA,EAAY;AAAA,KACb,CAAA;AAAA,EACH;AAEA,EAAA,OAAO,MAAA;AACT;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.esm.js","sources":["../../src/github/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';\nimport { trimEnd } from 'lodash';\nimport { isValidHost } from '../helpers';\n\nconst GITHUB_HOST = 'github.com';\nconst GITHUB_API_BASE_URL = 'https://api.github.com';\nconst GITHUB_RAW_BASE_URL = 'https://raw.githubusercontent.com';\n\n/**\n * The configuration parameters for a single GitHub integration.\n *\n * @public\n */\nexport type GithubIntegrationConfig = {\n /**\n * The host of the target that this matches on, e.g. \"github.com\"\n */\n host: string;\n\n /**\n * The base URL of the API of this provider, e.g. \"https://api.github.com\",\n * with no trailing slash.\n *\n * May be omitted specifically for GitHub; then it will be deduced.\n *\n * The API will always be preferred if both its base URL and a token are\n * present.\n */\n apiBaseUrl?: string;\n\n /**\n * The base URL of the raw fetch endpoint of this provider, e.g.\n * \"https://raw.githubusercontent.com\", with no trailing slash.\n *\n * May be omitted specifically for GitHub; then it will be deduced.\n *\n * The API will always be preferred if both its base URL and a token are\n * present.\n */\n rawBaseUrl?: string;\n\n /**\n * The authorization token to use for requests to this provider.\n *\n * If no token is specified, anonymous access is used.\n */\n token?: string;\n\n /**\n * The GitHub Apps configuration to use for requests to this provider.\n *\n * If no apps are specified, token or anonymous is used.\n */\n apps?: GithubAppConfig[];\n};\n\n/**\n * The configuration parameters for authenticating a GitHub Application.\n *\n * @remarks\n *\n * A GitHub Apps configuration can be generated using the `backstage-cli create-github-app` command.\n *\n * @public\n */\nexport type GithubAppConfig = {\n /**\n * Unique app identifier, found at https://github.com/organizations/$org/settings/apps/$AppName\n */\n appId: number;\n /**\n * The private key is used by the GitHub App integration to authenticate the app.\n * A private key can be generated from the app at https://github.com/organizations/$org/settings/apps/$AppName\n */\n privateKey: string;\n /**\n * Webhook secret can be configured at https://github.com/organizations/$org/settings/apps/$AppName\n */\n webhookSecret?: string;\n /**\n * Found at https://github.com/organizations/$org/settings/apps/$AppName\n */\n clientId: string;\n /**\n * Client secrets can be generated at https://github.com/organizations/$org/settings/apps/$AppName\n */\n clientSecret: string;\n /**\n * List of installation owners allowed to be used by this GitHub app. The GitHub UI does not provide a way to list the installations.\n * However you can list the installations with the GitHub API. You can find the list of installations here:\n * https://api.github.com/app/installations\n * The relevant documentation for this is here.\n * https://docs.github.com/en/rest/reference/apps#list-installations-for-the-authenticated-app--code-samples\n */\n allowedInstallationOwners?: string[];\n /**\n * If true, then an installation token will be issued for access when no other token is available.\n */\n publicAccess?: boolean;\n};\n\n/**\n * Reads a single GitHub integration config.\n *\n * @param config - The config object of a single integration\n * @public\n */\nexport function readGithubIntegrationConfig(\n config: Config,\n): GithubIntegrationConfig {\n const host = config.getOptionalString('host') ?? GITHUB_HOST;\n let apiBaseUrl = config.getOptionalString('apiBaseUrl');\n let rawBaseUrl = config.getOptionalString('rawBaseUrl');\n const token = config.getOptionalString('token')?.trim();\n const apps = config.getOptionalConfigArray('apps')?.map(c => ({\n appId: c.getNumber('appId'),\n clientId: c.getString('clientId'),\n clientSecret: c.getString('clientSecret'),\n webhookSecret: c.getOptionalString('webhookSecret'),\n privateKey: c.getString('privateKey'),\n allowedInstallationOwners: c.getOptionalStringArray(\n 'allowedInstallationOwners',\n ),\n publicAccess: c.getOptionalBoolean('publicAccess'),\n }));\n\n if (!isValidHost(host)) {\n throw new Error(\n `Invalid GitHub integration config, '${host}' is not a valid host`,\n );\n }\n\n if (apiBaseUrl) {\n apiBaseUrl = trimEnd(apiBaseUrl, '/');\n } else if (host === GITHUB_HOST) {\n apiBaseUrl = GITHUB_API_BASE_URL;\n }\n\n if (rawBaseUrl) {\n rawBaseUrl = trimEnd(rawBaseUrl, '/');\n } else if (host === GITHUB_HOST) {\n rawBaseUrl = GITHUB_RAW_BASE_URL;\n }\n\n return { host, apiBaseUrl, rawBaseUrl, token, apps };\n}\n\n/**\n * Reads a set of GitHub integration configs, and inserts some defaults for\n * public GitHub if not specified.\n *\n * @param configs - All of the integration config objects\n * @public\n */\nexport function readGithubIntegrationConfigs(\n configs: Config[],\n): GithubIntegrationConfig[] {\n // First read all the explicit integrations\n const result = configs.map(readGithubIntegrationConfig);\n\n // If no explicit github.com integration was added, put one in the list as\n // a convenience\n if (!result.some(c => c.host === GITHUB_HOST)) {\n result.push({\n host: GITHUB_HOST,\n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A,IAAI,UAAA,EAAY;AACd,IAAA,UAAA,GAAa,OAAA,CAAQ,YAAY,GAAG,CAAA;AAAA,EACtC,CAAA,MAAA,IAAW,SAAS,WAAA,EAAa;AAC/B,IAAA,UAAA,GAAa,mBAAA;AAAA,EACf;AAEA,EAAA,IAAI,UAAA,EAAY;AACd,IAAA,UAAA,GAAa,OAAA,CAAQ,YAAY,GAAG,CAAA;AAAA,EACtC,CAAA,MAAA,IAAW,SAAS,WAAA,EAAa;AAC/B,IAAA,UAAA,GAAa,mBAAA;AAAA,EACf;AAEA,EAAA,OAAO,EAAE,IAAA,EAAM,UAAA,EAAY,UAAA,EAAY,OAAO,IAAA,EAAK;AACrD;AASO,SAAS,6BACd,OAAA,EAC2B;AAE3B,EAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,GAAA,CAAI,2BAA2B,CAAA;AAItD,EAAA,IAAI,CAAC,MAAA,CAAO,IAAA,CAAK,OAAK,CAAA,CAAE,IAAA,KAAS,WAAW,CAAA,EAAG;AAC7C,IAAA,MAAA,CAAO,IAAA,CAAK;AAAA,MACV,IAAA,EAAM,WAAA;AAAA,MACN,UAAA,EAAY,mBAAA;AAAA,MACZ,UAAA,EAAY;AAAA,KACb,CAAA;AAAA,EACH;AAEA,EAAA,OAAO,MAAA;AACT
|
|
1
|
+
{"version":3,"file":"config.esm.js","sources":["../../src/github/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';\nimport { trimEnd } from 'lodash';\nimport { isValidHost } from '../helpers';\n\nconst GITHUB_HOST = 'github.com';\nconst GITHUB_API_BASE_URL = 'https://api.github.com';\nconst GITHUB_RAW_BASE_URL = 'https://raw.githubusercontent.com';\n\n/**\n * The configuration parameters for a single GitHub integration.\n *\n * @public\n */\nexport type GithubIntegrationConfig = {\n /**\n * The host of the target that this matches on, e.g. \"github.com\"\n */\n host: string;\n\n /**\n * The base URL of the API of this provider, e.g. \"https://api.github.com\",\n * with no trailing slash.\n *\n * May be omitted specifically for GitHub; then it will be deduced.\n *\n * The API will always be preferred if both its base URL and a token are\n * present.\n */\n apiBaseUrl?: string;\n\n /**\n * The base URL of the raw fetch endpoint of this provider, e.g.\n * \"https://raw.githubusercontent.com\", with no trailing slash.\n *\n * May be omitted specifically for GitHub; then it will be deduced.\n *\n * The API will always be preferred if both its base URL and a token are\n * present.\n */\n rawBaseUrl?: string;\n\n /**\n * The authorization token to use for requests to this provider.\n *\n * If no token is specified, anonymous access is used.\n */\n token?: string;\n\n /**\n * The GitHub Apps configuration to use for requests to this provider.\n *\n * If no apps are specified, token or anonymous is used.\n */\n apps?: GithubAppConfig[];\n};\n\n/**\n * The configuration parameters for authenticating a GitHub Application.\n *\n * @remarks\n *\n * A GitHub Apps configuration can be generated using the `backstage-cli create-github-app` command.\n *\n * @public\n */\nexport type GithubAppConfig = {\n /**\n * Unique app identifier, found at https://github.com/organizations/$org/settings/apps/$AppName\n */\n appId: number;\n /**\n * The private key is used by the GitHub App integration to authenticate the app.\n * A private key can be generated from the app at https://github.com/organizations/$org/settings/apps/$AppName\n */\n privateKey: string;\n /**\n * Webhook secret can be configured at https://github.com/organizations/$org/settings/apps/$AppName\n */\n webhookSecret?: string;\n /**\n * Found at https://github.com/organizations/$org/settings/apps/$AppName\n */\n clientId: string;\n /**\n * Client secrets can be generated at https://github.com/organizations/$org/settings/apps/$AppName\n */\n clientSecret: string;\n /**\n * List of installation owners allowed to be used by this GitHub app. The GitHub UI does not provide a way to list the installations.\n * However you can list the installations with the GitHub API. You can find the list of installations here:\n * https://api.github.com/app/installations\n * The relevant documentation for this is here.\n * https://docs.github.com/en/rest/reference/apps#list-installations-for-the-authenticated-app--code-samples\n */\n allowedInstallationOwners?: string[];\n /**\n * If true, then an installation token will be issued for access when no other token is available.\n */\n publicAccess?: boolean;\n};\n\n/**\n * Reads a single GitHub integration config.\n *\n * @param config - The config object of a single integration\n * @public\n */\nexport function readGithubIntegrationConfig(\n config: Config,\n): GithubIntegrationConfig {\n const host = config.getOptionalString('host') ?? GITHUB_HOST;\n let apiBaseUrl = config.getOptionalString('apiBaseUrl');\n let rawBaseUrl = config.getOptionalString('rawBaseUrl');\n const token = config.getOptionalString('token')?.trim();\n const apps = config.getOptionalConfigArray('apps')?.map(c => ({\n appId: c.getNumber('appId'),\n clientId: c.getString('clientId'),\n clientSecret: c.getString('clientSecret'),\n webhookSecret: c.getOptionalString('webhookSecret'),\n privateKey: c.getString('privateKey'),\n allowedInstallationOwners: c.getOptionalStringArray(\n 'allowedInstallationOwners',\n ),\n publicAccess: c.getOptionalBoolean('publicAccess'),\n }));\n\n if (!isValidHost(host)) {\n throw new Error(\n `Invalid GitHub integration config, '${host}' is not a valid host`,\n );\n }\n\n if (apiBaseUrl) {\n apiBaseUrl = trimEnd(apiBaseUrl, '/');\n } else if (host === GITHUB_HOST) {\n apiBaseUrl = GITHUB_API_BASE_URL;\n }\n\n if (rawBaseUrl) {\n rawBaseUrl = trimEnd(rawBaseUrl, '/');\n } else if (host === GITHUB_HOST) {\n rawBaseUrl = GITHUB_RAW_BASE_URL;\n }\n\n return { host, apiBaseUrl, rawBaseUrl, token, apps };\n}\n\n/**\n * Reads a set of GitHub integration configs, and inserts some defaults for\n * public GitHub if not specified.\n *\n * @param configs - All of the integration config objects\n * @public\n */\nexport function readGithubIntegrationConfigs(\n configs: Config[],\n): GithubIntegrationConfig[] {\n // First read all the explicit integrations\n const result = configs.map(readGithubIntegrationConfig);\n\n // If no explicit github.com integration was added, put one in the list as\n // a convenience\n if (!result.some(c => c.host === GITHUB_HOST)) {\n result.push({\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AA,EACF;AAEA,EAAA,IAAI,UAAA,EAAY;AACd,IAAA,UAAA,GAAa,OAAA,CAAQ,YAAY,GAAG,CAAA;AAAA,EACtC,CAAA,MAAA,IAAW,SAAS,WAAA,EAAa;AAC/B,IAAA,UAAA,GAAa,mBAAA;AAAA,EACf;AAEA,EAAA,IAAI,UAAA,EAAY;AACd,IAAA,UAAA,GAAa,OAAA,CAAQ,YAAY,GAAG,CAAA;AAAA,EACtC,CAAA,MAAA,IAAW,SAAS,WAAA,EAAa;AAC/B,IAAA,UAAA,GAAa,mBAAA;AAAA,EACf;AAEA,EAAA,OAAO,EAAE,IAAA,EAAM,UAAA,EAAY,UAAA,EAAY,OAAO,IAAA,EAAK;AACrD;AASO,SAAS,6BACd,OAAA,EAC2B;AAE3B,EAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,GAAA,CAAI,2BAA2B,CAAA;AAItD,EAAA,IAAI,CAAC,MAAA,CAAO,IAAA,CAAK,OAAK,CAAA,CAAE,IAAA,KAAS,WAAW,CAAA,EAAG;AAC7C,IAAA,MAAA,CAAO,IAAA,CAAK;AAAA,MACV,IAAA,EAAM,WAAA;AAAA,MACN,UAAA,EAAY,mBAAA;AAAA,MACZ,UAAA,EAAY;AAAA,KACb,CAAA;AAAA,EACH;AAEA,EAAA,OAAO,MAAA;AACT;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core.cjs.js","sources":["../../src/github/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 { GithubIntegrationConfig } from './config';\nimport { parseGitUrlSafe } from '../helpers';\nimport { GithubCredentials } from './types';\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://github.com/a/b/blob/branchname/path/to/c.yaml\n * to: https://api.github.com/repos/a/b/contents/path/to/c.yaml?ref=branchname\n * or: https://raw.githubusercontent.com/a/b/branchname/c.yaml\n *\n * @param url - A URL pointing to a file\n * @param config - The relevant provider config\n * @public\n */\nexport function getGithubFileFetchUrl(\n url: string,\n config: GithubIntegrationConfig,\n credentials: GithubCredentials,\n): string {\n try {\n const { owner, name, ref, filepathtype, filepath } = parseGitUrlSafe(url);\n if (\n !owner ||\n !name ||\n !ref ||\n // GitHub is automatically redirecting tree urls to blob urls so it's\n // fine to pass a tree url.\n (filepathtype !== 'blob' &&\n filepathtype !== 'raw' &&\n filepathtype !== 'tree')\n ) {\n throw new Error('Invalid GitHub URL or file path');\n }\n\n const pathWithoutSlash = filepath.replace(/^\\//, '');\n if (chooseEndpoint(config, credentials) === 'api') {\n return `${config.apiBaseUrl}/repos/${owner}/${name}/contents/${pathWithoutSlash}?ref=${ref}`;\n }\n return `${config.rawBaseUrl}/${owner}/${name}/${ref}/${pathWithoutSlash}`;\n } catch (e) {\n throw new Error(`Incorrect URL: ${url}, ${e}`);\n }\n}\n\nfunction chooseEndpoint(\n config: GithubIntegrationConfig,\n credentials: GithubCredentials,\n): 'api' | 'raw' {\n if (config.apiBaseUrl && (credentials.token || !config.rawBaseUrl)) {\n return 'api';\n }\n return 'raw';\n}\n"],"names":["parseGitUrlSafe"],"mappings":";;;;AAmCO,SAAS,qBAAA,CACd,GAAA,EACA,MAAA,EACA,WAAA,EACQ;AACR,EAAA,IAAI;AACF,IAAA,MAAM,EAAE,OAAO,IAAA,EAAM,GAAA,EAAK,cAAc,QAAA,EAAS,GAAIA,wBAAgB,GAAG,CAAA;AACxE,IAAA,IACE,CAAC,KAAA,IACD,CAAC,IAAA,IACD,CAAC,GAAA;AAAA;AAAA,IAGA,YAAA,KAAiB,MAAA,IAChB,YAAA,KAAiB,KAAA,IACjB,iBAAiB,MAAA,EACnB;AACA,MAAA,MAAM,IAAI,MAAM,iCAAiC,CAAA;AAAA,IACnD;AAEA,IAAA,MAAM,gBAAA,GAAmB,QAAA,CAAS,OAAA,CAAQ,KAAA,EAAO,EAAE,CAAA;AACnD,IAAA,IAAI,cAAA,CAAe,MAAA,EAAQ,WAAW,CAAA,KAAM,KAAA,EAAO;AACjD,MAAA,OAAO,CAAA,EAAG,MAAA,CAAO,UAAU,CAAA,OAAA,EAAU,KAAK,IAAI,IAAI,CAAA,UAAA,EAAa,gBAAgB,CAAA,KAAA,EAAQ,GAAG,CAAA,CAAA;AAAA,IAC5F;AACA,IAAA,OAAO,CAAA,EAAG,MAAA,CAAO,UAAU,CAAA,CAAA,EAAI,KAAK,IAAI,IAAI,CAAA,CAAA,EAAI,GAAG,CAAA,CAAA,EAAI,gBAAgB,CAAA,CAAA;AAAA,EACzE,SAAS,CAAA,EAAG;AACV,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,eAAA,EAAkB,GAAG,CAAA,EAAA,EAAK,CAAC,CAAA,CAAE,CAAA;AAAA,EAC/C;AACF;AAEA,SAAS,cAAA,CACP,QACA,WAAA,EACe;AACf,EAAA,IAAI,OAAO,UAAA,KAAe,WAAA,CAAY,KAAA,IAAS,CAAC,OAAO,UAAA,CAAA,EAAa;AAClE,IAAA,OAAO,KAAA;AAAA,EACT;AACA,EAAA,OAAO,KAAA;AACT
|
|
1
|
+
{"version":3,"file":"core.cjs.js","sources":["../../src/github/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 { GithubIntegrationConfig } from './config';\nimport { parseGitUrlSafe } from '../helpers';\nimport { GithubCredentials } from './types';\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://github.com/a/b/blob/branchname/path/to/c.yaml\n * to: https://api.github.com/repos/a/b/contents/path/to/c.yaml?ref=branchname\n * or: https://raw.githubusercontent.com/a/b/branchname/c.yaml\n *\n * @param url - A URL pointing to a file\n * @param config - The relevant provider config\n * @public\n */\nexport function getGithubFileFetchUrl(\n url: string,\n config: GithubIntegrationConfig,\n credentials: GithubCredentials,\n): string {\n try {\n const { owner, name, ref, filepathtype, filepath } = parseGitUrlSafe(url);\n if (\n !owner ||\n !name ||\n !ref ||\n // GitHub is automatically redirecting tree urls to blob urls so it's\n // fine to pass a tree url.\n (filepathtype !== 'blob' &&\n filepathtype !== 'raw' &&\n filepathtype !== 'tree')\n ) {\n throw new Error('Invalid GitHub URL or file path');\n }\n\n const pathWithoutSlash = filepath.replace(/^\\//, '');\n if (chooseEndpoint(config, credentials) === 'api') {\n return `${config.apiBaseUrl}/repos/${owner}/${name}/contents/${pathWithoutSlash}?ref=${ref}`;\n }\n return `${config.rawBaseUrl}/${owner}/${name}/${ref}/${pathWithoutSlash}`;\n } catch (e) {\n throw new Error(`Incorrect URL: ${url}, ${e}`);\n }\n}\n\nfunction chooseEndpoint(\n config: GithubIntegrationConfig,\n credentials: GithubCredentials,\n): 'api' | 'raw' {\n if (config.apiBaseUrl && (credentials.token || !config.rawBaseUrl)) {\n return 'api';\n }\n return 'raw';\n}\n"],"names":["parseGitUrlSafe"],"mappings":";;;;AAmCO,SAAS,qBAAA,CACd,GAAA,EACA,MAAA,EACA,WAAA,EACQ;AACR,EAAA,IAAI;AACF,IAAA,MAAM,EAAE,OAAO,IAAA,EAAM,GAAA,EAAK,cAAc,QAAA,EAAS,GAAIA,wBAAgB,GAAG,CAAA;AACxE,IAAA,IACE,CAAC,KAAA,IACD,CAAC,IAAA,IACD,CAAC,GAAA;AAAA;AAAA,IAGA,YAAA,KAAiB,MAAA,IAChB,YAAA,KAAiB,KAAA,IACjB,iBAAiB,MAAA,EACnB;AACA,MAAA,MAAM,IAAI,MAAM,iCAAiC,CAAA;AAAA,IACnD;AAEA,IAAA,MAAM,gBAAA,GAAmB,QAAA,CAAS,OAAA,CAAQ,KAAA,EAAO,EAAE,CAAA;AACnD,IAAA,IAAI,cAAA,CAAe,MAAA,EAAQ,WAAW,CAAA,KAAM,KAAA,EAAO;AACjD,MAAA,OAAO,CAAA,EAAG,MAAA,CAAO,UAAU,CAAA,OAAA,EAAU,KAAK,IAAI,IAAI,CAAA,UAAA,EAAa,gBAAgB,CAAA,KAAA,EAAQ,GAAG,CAAA,CAAA;AAAA,IAC5F;AACA,IAAA,OAAO,CAAA,EAAG,MAAA,CAAO,UAAU,CAAA,CAAA,EAAI,KAAK,IAAI,IAAI,CAAA,CAAA,EAAI,GAAG,CAAA,CAAA,EAAI,gBAAgB,CAAA,CAAA;AAAA,EACzE,SAAS,CAAA,EAAG;AACV,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,eAAA,EAAkB,GAAG,CAAA,EAAA,EAAK,CAAC,CAAA,CAAE,CAAA;AAAA,EAC/C;AACF;AAEA,SAAS,cAAA,CACP,QACA,WAAA,EACe;AACf,EAAA,IAAI,OAAO,UAAA,KAAe,WAAA,CAAY,KAAA,IAAS,CAAC,OAAO,UAAA,CAAA,EAAa;AAClE,IAAA,OAAO,KAAA;AAAA,EACT;AACA,EAAA,OAAO,KAAA;AACT;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core.esm.js","sources":["../../src/github/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 { GithubIntegrationConfig } from './config';\nimport { parseGitUrlSafe } from '../helpers';\nimport { GithubCredentials } from './types';\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://github.com/a/b/blob/branchname/path/to/c.yaml\n * to: https://api.github.com/repos/a/b/contents/path/to/c.yaml?ref=branchname\n * or: https://raw.githubusercontent.com/a/b/branchname/c.yaml\n *\n * @param url - A URL pointing to a file\n * @param config - The relevant provider config\n * @public\n */\nexport function getGithubFileFetchUrl(\n url: string,\n config: GithubIntegrationConfig,\n credentials: GithubCredentials,\n): string {\n try {\n const { owner, name, ref, filepathtype, filepath } = parseGitUrlSafe(url);\n if (\n !owner ||\n !name ||\n !ref ||\n // GitHub is automatically redirecting tree urls to blob urls so it's\n // fine to pass a tree url.\n (filepathtype !== 'blob' &&\n filepathtype !== 'raw' &&\n filepathtype !== 'tree')\n ) {\n throw new Error('Invalid GitHub URL or file path');\n }\n\n const pathWithoutSlash = filepath.replace(/^\\//, '');\n if (chooseEndpoint(config, credentials) === 'api') {\n return `${config.apiBaseUrl}/repos/${owner}/${name}/contents/${pathWithoutSlash}?ref=${ref}`;\n }\n return `${config.rawBaseUrl}/${owner}/${name}/${ref}/${pathWithoutSlash}`;\n } catch (e) {\n throw new Error(`Incorrect URL: ${url}, ${e}`);\n }\n}\n\nfunction chooseEndpoint(\n config: GithubIntegrationConfig,\n credentials: GithubCredentials,\n): 'api' | 'raw' {\n if (config.apiBaseUrl && (credentials.token || !config.rawBaseUrl)) {\n return 'api';\n }\n return 'raw';\n}\n"],"names":[],"mappings":";;AAmCO,SAAS,qBAAA,CACd,GAAA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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 { GithubIntegrationConfig } from './config';\nimport { parseGitUrlSafe } from '../helpers';\nimport { GithubCredentials } from './types';\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://github.com/a/b/blob/branchname/path/to/c.yaml\n * to: https://api.github.com/repos/a/b/contents/path/to/c.yaml?ref=branchname\n * or: https://raw.githubusercontent.com/a/b/branchname/c.yaml\n *\n * @param url - A URL pointing to a file\n * @param config - The relevant provider config\n * @public\n */\nexport function getGithubFileFetchUrl(\n url: string,\n config: GithubIntegrationConfig,\n credentials: GithubCredentials,\n): string {\n try {\n const { owner, name, ref, filepathtype, filepath } = parseGitUrlSafe(url);\n if (\n !owner ||\n !name ||\n !ref ||\n // GitHub is automatically redirecting tree urls to blob urls so it's\n // fine to pass a tree url.\n (filepathtype !== 'blob' &&\n filepathtype !== 'raw' &&\n filepathtype !== 'tree')\n ) {\n throw new Error('Invalid GitHub URL or file path');\n }\n\n const pathWithoutSlash = filepath.replace(/^\\//, '');\n if (chooseEndpoint(config, credentials) === 'api') {\n return `${config.apiBaseUrl}/repos/${owner}/${name}/contents/${pathWithoutSlash}?ref=${ref}`;\n }\n return `${config.rawBaseUrl}/${owner}/${name}/${ref}/${pathWithoutSlash}`;\n } catch (e) {\n throw new Error(`Incorrect URL: ${url}, ${e}`);\n }\n}\n\nfunction chooseEndpoint(\n config: GithubIntegrationConfig,\n credentials: GithubCredentials,\n): 'api' | 'raw' {\n if (config.apiBaseUrl && (credentials.token || !config.rawBase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