🚀 feat(_route): add dev to origin

This commit is contained in:
eshanized
2024-12-23 02:19:28 +05:30
parent 0bca0ca1d7
commit 937b1a56ab
16382 changed files with 2985935 additions and 1967 deletions

View File

@@ -0,0 +1,21 @@
The MIT License
Copyright (c) 2019 Octokit contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,490 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// pkg/dist-src/index.js
var dist_src_exports = {};
__export(dist_src_exports, {
createAppAuth: () => createAppAuth,
createOAuthUserAuth: () => import_auth_oauth_user2.createOAuthUserAuth
});
module.exports = __toCommonJS(dist_src_exports);
var import_universal_user_agent = require("universal-user-agent");
var import_request = require("@octokit/request");
var import_auth_oauth_app = require("@octokit/auth-oauth-app");
// pkg/dist-src/auth.js
var import_deprecation = require("deprecation");
var OAuthAppAuth = __toESM(require("@octokit/auth-oauth-app"));
// pkg/dist-src/get-app-authentication.js
var import_universal_github_app_jwt = require("universal-github-app-jwt");
async function getAppAuthentication({
appId,
privateKey,
timeDifference
}) {
try {
const appAuthentication = await (0, import_universal_github_app_jwt.githubAppJwt)({
id: +appId,
privateKey,
now: timeDifference && Math.floor(Date.now() / 1e3) + timeDifference
});
return {
type: "app",
token: appAuthentication.token,
appId: appAuthentication.appId,
expiresAt: new Date(appAuthentication.expiration * 1e3).toISOString()
};
} catch (error) {
if (privateKey === "-----BEGIN RSA PRIVATE KEY-----") {
throw new Error(
"The 'privateKey` option contains only the first line '-----BEGIN RSA PRIVATE KEY-----'. If you are setting it using a `.env` file, make sure it is set on a single line with newlines replaced by '\n'"
);
} else {
throw error;
}
}
}
// pkg/dist-src/cache.js
var import_lru_cache = require("lru-cache");
function getCache() {
return new import_lru_cache.LRUCache({
// cache max. 15000 tokens, that will use less than 10mb memory
max: 15e3,
// Cache for 1 minute less than GitHub expiry
ttl: 1e3 * 60 * 59
});
}
async function get(cache, options) {
const cacheKey = optionsToCacheKey(options);
const result = await cache.get(cacheKey);
if (!result) {
return;
}
const [
token,
createdAt,
expiresAt,
repositorySelection,
permissionsString,
singleFileName
] = result.split("|");
const permissions = options.permissions || permissionsString.split(/,/).reduce((permissions2, string) => {
if (/!$/.test(string)) {
permissions2[string.slice(0, -1)] = "write";
} else {
permissions2[string] = "read";
}
return permissions2;
}, {});
return {
token,
createdAt,
expiresAt,
permissions,
repositoryIds: options.repositoryIds,
repositoryNames: options.repositoryNames,
singleFileName,
repositorySelection
};
}
async function set(cache, options, data) {
const key = optionsToCacheKey(options);
const permissionsString = options.permissions ? "" : Object.keys(data.permissions).map(
(name) => `${name}${data.permissions[name] === "write" ? "!" : ""}`
).join(",");
const value = [
data.token,
data.createdAt,
data.expiresAt,
data.repositorySelection,
permissionsString,
data.singleFileName
].join("|");
await cache.set(key, value);
}
function optionsToCacheKey({
installationId,
permissions = {},
repositoryIds = [],
repositoryNames = []
}) {
const permissionsString = Object.keys(permissions).sort().map((name) => permissions[name] === "read" ? name : `${name}!`).join(",");
const repositoryIdsString = repositoryIds.sort().join(",");
const repositoryNamesString = repositoryNames.join(",");
return [
installationId,
repositoryIdsString,
repositoryNamesString,
permissionsString
].filter(Boolean).join("|");
}
// pkg/dist-src/to-token-authentication.js
function toTokenAuthentication({
installationId,
token,
createdAt,
expiresAt,
repositorySelection,
permissions,
repositoryIds,
repositoryNames,
singleFileName
}) {
return Object.assign(
{
type: "token",
tokenType: "installation",
token,
installationId,
permissions,
createdAt,
expiresAt,
repositorySelection
},
repositoryIds ? { repositoryIds } : null,
repositoryNames ? { repositoryNames } : null,
singleFileName ? { singleFileName } : null
);
}
// pkg/dist-src/get-installation-authentication.js
async function getInstallationAuthentication(state, options, customRequest) {
const installationId = Number(options.installationId || state.installationId);
if (!installationId) {
throw new Error(
"[@octokit/auth-app] installationId option is required for installation authentication."
);
}
if (options.factory) {
const { type, factory, oauthApp, ...factoryAuthOptions } = {
...state,
...options
};
return factory(factoryAuthOptions);
}
const optionsWithInstallationTokenFromState = Object.assign(
{ installationId },
options
);
if (!options.refresh) {
const result = await get(
state.cache,
optionsWithInstallationTokenFromState
);
if (result) {
const {
token: token2,
createdAt: createdAt2,
expiresAt: expiresAt2,
permissions: permissions2,
repositoryIds: repositoryIds2,
repositoryNames: repositoryNames2,
singleFileName: singleFileName2,
repositorySelection: repositorySelection2
} = result;
return toTokenAuthentication({
installationId,
token: token2,
createdAt: createdAt2,
expiresAt: expiresAt2,
permissions: permissions2,
repositorySelection: repositorySelection2,
repositoryIds: repositoryIds2,
repositoryNames: repositoryNames2,
singleFileName: singleFileName2
});
}
}
const appAuthentication = await getAppAuthentication(state);
const request = customRequest || state.request;
const {
data: {
token,
expires_at: expiresAt,
repositories,
permissions: permissionsOptional,
repository_selection: repositorySelectionOptional,
single_file: singleFileName
}
} = await request("POST /app/installations/{installation_id}/access_tokens", {
installation_id: installationId,
repository_ids: options.repositoryIds,
repositories: options.repositoryNames,
permissions: options.permissions,
mediaType: {
previews: ["machine-man"]
},
headers: {
authorization: `bearer ${appAuthentication.token}`
}
});
const permissions = permissionsOptional || {};
const repositorySelection = repositorySelectionOptional || "all";
const repositoryIds = repositories ? repositories.map((r) => r.id) : void 0;
const repositoryNames = repositories ? repositories.map((repo) => repo.name) : void 0;
const createdAt = (/* @__PURE__ */ new Date()).toISOString();
await set(state.cache, optionsWithInstallationTokenFromState, {
token,
createdAt,
expiresAt,
repositorySelection,
permissions,
repositoryIds,
repositoryNames,
singleFileName
});
return toTokenAuthentication({
installationId,
token,
createdAt,
expiresAt,
repositorySelection,
permissions,
repositoryIds,
repositoryNames,
singleFileName
});
}
// pkg/dist-src/auth.js
async function auth(state, authOptions) {
switch (authOptions.type) {
case "app":
return getAppAuthentication(state);
case "oauth":
state.log.warn(
// @ts-expect-error `log.warn()` expects string
new import_deprecation.Deprecation(
`[@octokit/auth-app] {type: "oauth"} is deprecated. Use {type: "oauth-app"} instead`
)
);
case "oauth-app":
return state.oauthApp({ type: "oauth-app" });
case "installation":
authOptions;
return getInstallationAuthentication(state, {
...authOptions,
type: "installation"
});
case "oauth-user":
return state.oauthApp(authOptions);
default:
throw new Error(`Invalid auth type: ${authOptions.type}`);
}
}
// pkg/dist-src/hook.js
var import_auth_oauth_user = require("@octokit/auth-oauth-user");
var import_request_error = require("@octokit/request-error");
// pkg/dist-src/requires-app-auth.js
var PATHS = [
"/app",
"/app/hook/config",
"/app/hook/deliveries",
"/app/hook/deliveries/{delivery_id}",
"/app/hook/deliveries/{delivery_id}/attempts",
"/app/installations",
"/app/installations/{installation_id}",
"/app/installations/{installation_id}/access_tokens",
"/app/installations/{installation_id}/suspended",
"/app/installation-requests",
"/marketplace_listing/accounts/{account_id}",
"/marketplace_listing/plan",
"/marketplace_listing/plans",
"/marketplace_listing/plans/{plan_id}/accounts",
"/marketplace_listing/stubbed/accounts/{account_id}",
"/marketplace_listing/stubbed/plan",
"/marketplace_listing/stubbed/plans",
"/marketplace_listing/stubbed/plans/{plan_id}/accounts",
"/orgs/{org}/installation",
"/repos/{owner}/{repo}/installation",
"/users/{username}/installation"
];
function routeMatcher(paths) {
const regexes = paths.map(
(p) => p.split("/").map((c) => c.startsWith("{") ? "(?:.+?)" : c).join("/")
);
const regex = `^(?:${regexes.map((r) => `(?:${r})`).join("|")})$`;
return new RegExp(regex, "i");
}
var REGEX = routeMatcher(PATHS);
function requiresAppAuth(url) {
return !!url && REGEX.test(url.split("?")[0]);
}
// pkg/dist-src/hook.js
var FIVE_SECONDS_IN_MS = 5 * 1e3;
function isNotTimeSkewError(error) {
return !(error.message.match(
/'Expiration time' claim \('exp'\) must be a numeric value representing the future time at which the assertion expires/
) || error.message.match(
/'Issued at' claim \('iat'\) must be an Integer representing the time that the assertion was issued/
));
}
async function hook(state, request, route, parameters) {
const endpoint = request.endpoint.merge(route, parameters);
const url = endpoint.url;
if (/\/login\/oauth\/access_token$/.test(url)) {
return request(endpoint);
}
if (requiresAppAuth(url.replace(request.endpoint.DEFAULTS.baseUrl, ""))) {
const { token: token2 } = await getAppAuthentication(state);
endpoint.headers.authorization = `bearer ${token2}`;
let response;
try {
response = await request(endpoint);
} catch (error) {
if (isNotTimeSkewError(error)) {
throw error;
}
if (typeof error.response.headers.date === "undefined") {
throw error;
}
const diff = Math.floor(
(Date.parse(error.response.headers.date) - Date.parse((/* @__PURE__ */ new Date()).toString())) / 1e3
);
state.log.warn(error.message);
state.log.warn(
`[@octokit/auth-app] GitHub API time and system time are different by ${diff} seconds. Retrying request with the difference accounted for.`
);
const { token: token3 } = await getAppAuthentication({
...state,
timeDifference: diff
});
endpoint.headers.authorization = `bearer ${token3}`;
return request(endpoint);
}
return response;
}
if ((0, import_auth_oauth_user.requiresBasicAuth)(url)) {
const authentication = await state.oauthApp({ type: "oauth-app" });
endpoint.headers.authorization = authentication.headers.authorization;
return request(endpoint);
}
const { token, createdAt } = await getInstallationAuthentication(
state,
// @ts-expect-error TBD
{},
request.defaults({ baseUrl: endpoint.baseUrl })
);
endpoint.headers.authorization = `token ${token}`;
return sendRequestWithRetries(
state,
request,
endpoint,
createdAt
);
}
async function sendRequestWithRetries(state, request, options, createdAt, retries = 0) {
const timeSinceTokenCreationInMs = +/* @__PURE__ */ new Date() - +new Date(createdAt);
try {
return await request(options);
} catch (error) {
if (error.status !== 401) {
throw error;
}
if (timeSinceTokenCreationInMs >= FIVE_SECONDS_IN_MS) {
if (retries > 0) {
error.message = `After ${retries} retries within ${timeSinceTokenCreationInMs / 1e3}s of creating the installation access token, the response remains 401. At this point, the cause may be an authentication problem or a system outage. Please check https://www.githubstatus.com for status information`;
}
throw error;
}
++retries;
const awaitTime = retries * 1e3;
state.log.warn(
`[@octokit/auth-app] Retrying after 401 response to account for token replication delay (retry: ${retries}, wait: ${awaitTime / 1e3}s)`
);
await new Promise((resolve) => setTimeout(resolve, awaitTime));
return sendRequestWithRetries(state, request, options, createdAt, retries);
}
}
// pkg/dist-src/version.js
var VERSION = "6.1.3";
// pkg/dist-src/index.js
var import_auth_oauth_user2 = require("@octokit/auth-oauth-user");
function createAppAuth(options) {
if (!options.appId) {
throw new Error("[@octokit/auth-app] appId option is required");
}
if (!Number.isFinite(+options.appId)) {
throw new Error(
"[@octokit/auth-app] appId option must be a number or numeric string"
);
}
if (!options.privateKey) {
throw new Error("[@octokit/auth-app] privateKey option is required");
}
if ("installationId" in options && !options.installationId) {
throw new Error(
"[@octokit/auth-app] installationId is set to a falsy value"
);
}
const log = Object.assign(
{
warn: console.warn.bind(console)
},
options.log
);
const request = options.request || import_request.request.defaults({
headers: {
"user-agent": `octokit-auth-app.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`
}
});
const state = Object.assign(
{
request,
cache: getCache()
},
options,
options.installationId ? { installationId: Number(options.installationId) } : {},
{
log,
oauthApp: (0, import_auth_oauth_app.createOAuthAppAuth)({
clientType: "github-app",
clientId: options.clientId || "",
clientSecret: options.clientSecret || "",
request
})
}
);
return Object.assign(auth.bind(null, state), {
hook: hook.bind(null, state)
});
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
createAppAuth,
createOAuthUserAuth
});

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,32 @@
import { Deprecation } from "deprecation";
import * as OAuthAppAuth from "@octokit/auth-oauth-app";
import { getAppAuthentication } from "./get-app-authentication.js";
import { getInstallationAuthentication } from "./get-installation-authentication.js";
async function auth(state, authOptions) {
switch (authOptions.type) {
case "app":
return getAppAuthentication(state);
case "oauth":
state.log.warn(
// @ts-expect-error `log.warn()` expects string
new Deprecation(
`[@octokit/auth-app] {type: "oauth"} is deprecated. Use {type: "oauth-app"} instead`
)
);
case "oauth-app":
return state.oauthApp({ type: "oauth-app" });
case "installation":
authOptions;
return getInstallationAuthentication(state, {
...authOptions,
type: "installation"
});
case "oauth-user":
return state.oauthApp(authOptions);
default:
throw new Error(`Invalid auth type: ${authOptions.type}`);
}
}
export {
auth
};

View File

@@ -0,0 +1,78 @@
import { LRUCache } from "lru-cache";
function getCache() {
return new LRUCache({
// cache max. 15000 tokens, that will use less than 10mb memory
max: 15e3,
// Cache for 1 minute less than GitHub expiry
ttl: 1e3 * 60 * 59
});
}
async function get(cache, options) {
const cacheKey = optionsToCacheKey(options);
const result = await cache.get(cacheKey);
if (!result) {
return;
}
const [
token,
createdAt,
expiresAt,
repositorySelection,
permissionsString,
singleFileName
] = result.split("|");
const permissions = options.permissions || permissionsString.split(/,/).reduce((permissions2, string) => {
if (/!$/.test(string)) {
permissions2[string.slice(0, -1)] = "write";
} else {
permissions2[string] = "read";
}
return permissions2;
}, {});
return {
token,
createdAt,
expiresAt,
permissions,
repositoryIds: options.repositoryIds,
repositoryNames: options.repositoryNames,
singleFileName,
repositorySelection
};
}
async function set(cache, options, data) {
const key = optionsToCacheKey(options);
const permissionsString = options.permissions ? "" : Object.keys(data.permissions).map(
(name) => `${name}${data.permissions[name] === "write" ? "!" : ""}`
).join(",");
const value = [
data.token,
data.createdAt,
data.expiresAt,
data.repositorySelection,
permissionsString,
data.singleFileName
].join("|");
await cache.set(key, value);
}
function optionsToCacheKey({
installationId,
permissions = {},
repositoryIds = [],
repositoryNames = []
}) {
const permissionsString = Object.keys(permissions).sort().map((name) => permissions[name] === "read" ? name : `${name}!`).join(",");
const repositoryIdsString = repositoryIds.sort().join(",");
const repositoryNamesString = repositoryNames.join(",");
return [
installationId,
repositoryIdsString,
repositoryNamesString,
permissionsString
].filter(Boolean).join("|");
}
export {
get,
getCache,
set
};

View File

@@ -0,0 +1,31 @@
import { githubAppJwt } from "universal-github-app-jwt";
async function getAppAuthentication({
appId,
privateKey,
timeDifference
}) {
try {
const appAuthentication = await githubAppJwt({
id: +appId,
privateKey,
now: timeDifference && Math.floor(Date.now() / 1e3) + timeDifference
});
return {
type: "app",
token: appAuthentication.token,
appId: appAuthentication.appId,
expiresAt: new Date(appAuthentication.expiration * 1e3).toISOString()
};
} catch (error) {
if (privateKey === "-----BEGIN RSA PRIVATE KEY-----") {
throw new Error(
"The 'privateKey` option contains only the first line '-----BEGIN RSA PRIVATE KEY-----'. If you are setting it using a `.env` file, make sure it is set on a single line with newlines replaced by '\n'"
);
} else {
throw error;
}
}
}
export {
getAppAuthentication
};

View File

@@ -0,0 +1,103 @@
import { get, set } from "./cache.js";
import { getAppAuthentication } from "./get-app-authentication.js";
import { toTokenAuthentication } from "./to-token-authentication.js";
async function getInstallationAuthentication(state, options, customRequest) {
const installationId = Number(options.installationId || state.installationId);
if (!installationId) {
throw new Error(
"[@octokit/auth-app] installationId option is required for installation authentication."
);
}
if (options.factory) {
const { type, factory, oauthApp, ...factoryAuthOptions } = {
...state,
...options
};
return factory(factoryAuthOptions);
}
const optionsWithInstallationTokenFromState = Object.assign(
{ installationId },
options
);
if (!options.refresh) {
const result = await get(
state.cache,
optionsWithInstallationTokenFromState
);
if (result) {
const {
token: token2,
createdAt: createdAt2,
expiresAt: expiresAt2,
permissions: permissions2,
repositoryIds: repositoryIds2,
repositoryNames: repositoryNames2,
singleFileName: singleFileName2,
repositorySelection: repositorySelection2
} = result;
return toTokenAuthentication({
installationId,
token: token2,
createdAt: createdAt2,
expiresAt: expiresAt2,
permissions: permissions2,
repositorySelection: repositorySelection2,
repositoryIds: repositoryIds2,
repositoryNames: repositoryNames2,
singleFileName: singleFileName2
});
}
}
const appAuthentication = await getAppAuthentication(state);
const request = customRequest || state.request;
const {
data: {
token,
expires_at: expiresAt,
repositories,
permissions: permissionsOptional,
repository_selection: repositorySelectionOptional,
single_file: singleFileName
}
} = await request("POST /app/installations/{installation_id}/access_tokens", {
installation_id: installationId,
repository_ids: options.repositoryIds,
repositories: options.repositoryNames,
permissions: options.permissions,
mediaType: {
previews: ["machine-man"]
},
headers: {
authorization: `bearer ${appAuthentication.token}`
}
});
const permissions = permissionsOptional || {};
const repositorySelection = repositorySelectionOptional || "all";
const repositoryIds = repositories ? repositories.map((r) => r.id) : void 0;
const repositoryNames = repositories ? repositories.map((repo) => repo.name) : void 0;
const createdAt = (/* @__PURE__ */ new Date()).toISOString();
await set(state.cache, optionsWithInstallationTokenFromState, {
token,
createdAt,
expiresAt,
repositorySelection,
permissions,
repositoryIds,
repositoryNames,
singleFileName
});
return toTokenAuthentication({
installationId,
token,
createdAt,
expiresAt,
repositorySelection,
permissions,
repositoryIds,
repositoryNames,
singleFileName
});
}
export {
getInstallationAuthentication
};

View File

@@ -0,0 +1,93 @@
import { requiresBasicAuth } from "@octokit/auth-oauth-user";
import { RequestError } from "@octokit/request-error";
import { getAppAuthentication } from "./get-app-authentication.js";
import { getInstallationAuthentication } from "./get-installation-authentication.js";
import { requiresAppAuth } from "./requires-app-auth.js";
const FIVE_SECONDS_IN_MS = 5 * 1e3;
function isNotTimeSkewError(error) {
return !(error.message.match(
/'Expiration time' claim \('exp'\) must be a numeric value representing the future time at which the assertion expires/
) || error.message.match(
/'Issued at' claim \('iat'\) must be an Integer representing the time that the assertion was issued/
));
}
async function hook(state, request, route, parameters) {
const endpoint = request.endpoint.merge(route, parameters);
const url = endpoint.url;
if (/\/login\/oauth\/access_token$/.test(url)) {
return request(endpoint);
}
if (requiresAppAuth(url.replace(request.endpoint.DEFAULTS.baseUrl, ""))) {
const { token: token2 } = await getAppAuthentication(state);
endpoint.headers.authorization = `bearer ${token2}`;
let response;
try {
response = await request(endpoint);
} catch (error) {
if (isNotTimeSkewError(error)) {
throw error;
}
if (typeof error.response.headers.date === "undefined") {
throw error;
}
const diff = Math.floor(
(Date.parse(error.response.headers.date) - Date.parse((/* @__PURE__ */ new Date()).toString())) / 1e3
);
state.log.warn(error.message);
state.log.warn(
`[@octokit/auth-app] GitHub API time and system time are different by ${diff} seconds. Retrying request with the difference accounted for.`
);
const { token: token3 } = await getAppAuthentication({
...state,
timeDifference: diff
});
endpoint.headers.authorization = `bearer ${token3}`;
return request(endpoint);
}
return response;
}
if (requiresBasicAuth(url)) {
const authentication = await state.oauthApp({ type: "oauth-app" });
endpoint.headers.authorization = authentication.headers.authorization;
return request(endpoint);
}
const { token, createdAt } = await getInstallationAuthentication(
state,
// @ts-expect-error TBD
{},
request.defaults({ baseUrl: endpoint.baseUrl })
);
endpoint.headers.authorization = `token ${token}`;
return sendRequestWithRetries(
state,
request,
endpoint,
createdAt
);
}
async function sendRequestWithRetries(state, request, options, createdAt, retries = 0) {
const timeSinceTokenCreationInMs = +/* @__PURE__ */ new Date() - +new Date(createdAt);
try {
return await request(options);
} catch (error) {
if (error.status !== 401) {
throw error;
}
if (timeSinceTokenCreationInMs >= FIVE_SECONDS_IN_MS) {
if (retries > 0) {
error.message = `After ${retries} retries within ${timeSinceTokenCreationInMs / 1e3}s of creating the installation access token, the response remains 401. At this point, the cause may be an authentication problem or a system outage. Please check https://www.githubstatus.com for status information`;
}
throw error;
}
++retries;
const awaitTime = retries * 1e3;
state.log.warn(
`[@octokit/auth-app] Retrying after 401 response to account for token replication delay (retry: ${retries}, wait: ${awaitTime / 1e3}s)`
);
await new Promise((resolve) => setTimeout(resolve, awaitTime));
return sendRequestWithRetries(state, request, options, createdAt, retries);
}
}
export {
hook
};

View File

@@ -0,0 +1,61 @@
import { getUserAgent } from "universal-user-agent";
import { request as defaultRequest } from "@octokit/request";
import { createOAuthAppAuth } from "@octokit/auth-oauth-app";
import { auth } from "./auth.js";
import { hook } from "./hook.js";
import { getCache } from "./cache.js";
import { VERSION } from "./version.js";
import { createOAuthUserAuth } from "@octokit/auth-oauth-user";
function createAppAuth(options) {
if (!options.appId) {
throw new Error("[@octokit/auth-app] appId option is required");
}
if (!Number.isFinite(+options.appId)) {
throw new Error(
"[@octokit/auth-app] appId option must be a number or numeric string"
);
}
if (!options.privateKey) {
throw new Error("[@octokit/auth-app] privateKey option is required");
}
if ("installationId" in options && !options.installationId) {
throw new Error(
"[@octokit/auth-app] installationId is set to a falsy value"
);
}
const log = Object.assign(
{
warn: console.warn.bind(console)
},
options.log
);
const request = options.request || defaultRequest.defaults({
headers: {
"user-agent": `octokit-auth-app.js/${VERSION} ${getUserAgent()}`
}
});
const state = Object.assign(
{
request,
cache: getCache()
},
options,
options.installationId ? { installationId: Number(options.installationId) } : {},
{
log,
oauthApp: createOAuthAppAuth({
clientType: "github-app",
clientId: options.clientId || "",
clientSecret: options.clientSecret || "",
request
})
}
);
return Object.assign(auth.bind(null, state), {
hook: hook.bind(null, state)
});
}
export {
createAppAuth,
createOAuthUserAuth
};

View File

@@ -0,0 +1,37 @@
const PATHS = [
"/app",
"/app/hook/config",
"/app/hook/deliveries",
"/app/hook/deliveries/{delivery_id}",
"/app/hook/deliveries/{delivery_id}/attempts",
"/app/installations",
"/app/installations/{installation_id}",
"/app/installations/{installation_id}/access_tokens",
"/app/installations/{installation_id}/suspended",
"/app/installation-requests",
"/marketplace_listing/accounts/{account_id}",
"/marketplace_listing/plan",
"/marketplace_listing/plans",
"/marketplace_listing/plans/{plan_id}/accounts",
"/marketplace_listing/stubbed/accounts/{account_id}",
"/marketplace_listing/stubbed/plan",
"/marketplace_listing/stubbed/plans",
"/marketplace_listing/stubbed/plans/{plan_id}/accounts",
"/orgs/{org}/installation",
"/repos/{owner}/{repo}/installation",
"/users/{username}/installation"
];
function routeMatcher(paths) {
const regexes = paths.map(
(p) => p.split("/").map((c) => c.startsWith("{") ? "(?:.+?)" : c).join("/")
);
const regex = `^(?:${regexes.map((r) => `(?:${r})`).join("|")})$`;
return new RegExp(regex, "i");
}
const REGEX = routeMatcher(PATHS);
function requiresAppAuth(url) {
return !!url && REGEX.test(url.split("?")[0]);
}
export {
requiresAppAuth
};

View File

@@ -0,0 +1,30 @@
function toTokenAuthentication({
installationId,
token,
createdAt,
expiresAt,
repositorySelection,
permissions,
repositoryIds,
repositoryNames,
singleFileName
}) {
return Object.assign(
{
type: "token",
tokenType: "installation",
token,
installationId,
permissions,
createdAt,
expiresAt,
repositorySelection
},
repositoryIds ? { repositoryIds } : null,
repositoryNames ? { repositoryNames } : null,
singleFileName ? { singleFileName } : null
);
}
export {
toTokenAuthentication
};

View File

@@ -0,0 +1,4 @@
const VERSION = "6.1.3";
export {
VERSION
};

View File

@@ -0,0 +1,20 @@
import * as OAuthAppAuth from "@octokit/auth-oauth-app";
import type { State, AppAuthOptions, AppAuthentication, OAuthAppAuthentication, OAuthAppAuthOptions, InstallationAuthOptions, InstallationAccessTokenAuthentication, GitHubAppUserAuthentication, GitHubAppUserAuthenticationWithExpiration, OAuthWebFlowAuthOptions, OAuthDeviceFlowAuthOptions } from "./types.js";
/** GitHub App authentication */
export declare function auth(state: State, authOptions: AppAuthOptions): Promise<AppAuthentication>;
/** OAuth App authentication */
export declare function auth(state: State, authOptions: OAuthAppAuthOptions): Promise<OAuthAppAuthentication>;
/** Installation authentication */
export declare function auth(state: State, authOptions: InstallationAuthOptions): Promise<InstallationAccessTokenAuthentication>;
/** User Authentication via OAuth web flow */
export declare function auth(state: State, authOptions: OAuthWebFlowAuthOptions): Promise<GitHubAppUserAuthentication | GitHubAppUserAuthenticationWithExpiration>;
/** GitHub App Web flow with `factory` option */
export declare function auth<T = unknown>(state: State, authOptions: OAuthWebFlowAuthOptions & {
factory: OAuthAppAuth.FactoryGitHubWebFlow<T>;
}): Promise<T>;
/** User Authentication via OAuth Device flow */
export declare function auth(state: State, authOptions: OAuthDeviceFlowAuthOptions): Promise<GitHubAppUserAuthentication | GitHubAppUserAuthenticationWithExpiration>;
/** GitHub App Device flow with `factory` option */
export declare function auth<T = unknown>(state: State, authOptions: OAuthDeviceFlowAuthOptions & {
factory: OAuthAppAuth.FactoryGitHubDeviceFlow<T>;
}): Promise<T>;

View File

@@ -0,0 +1,5 @@
import { LRUCache } from "lru-cache";
import type { InstallationAuthOptions, Cache, CacheData, InstallationAccessTokenData } from "./types";
export declare function getCache(): LRUCache<number, string, unknown>;
export declare function get(cache: Cache, options: InstallationAuthOptions): Promise<InstallationAccessTokenData | void>;
export declare function set(cache: Cache, options: InstallationAuthOptions, data: CacheData): Promise<void>;

View File

@@ -0,0 +1,4 @@
import type { AppAuthentication, State } from "./types.js";
export declare function getAppAuthentication({ appId, privateKey, timeDifference, }: State & {
timeDifference?: number;
}): Promise<AppAuthentication>;

View File

@@ -0,0 +1,2 @@
import type { InstallationAuthOptions, InstallationAccessTokenAuthentication, RequestInterface, State } from "./types.js";
export declare function getInstallationAuthentication(state: State, options: InstallationAuthOptions, customRequest?: RequestInterface): Promise<InstallationAccessTokenAuthentication>;

View File

@@ -0,0 +1,2 @@
import type { AnyResponse, EndpointOptions, RequestParameters, RequestInterface, Route, State } from "./types.js";
export declare function hook(state: State, request: RequestInterface, route: Route | EndpointOptions, parameters?: RequestParameters): Promise<AnyResponse>;

View File

@@ -0,0 +1,4 @@
import type { AuthInterface, StrategyOptions } from "./types.js";
export { createOAuthUserAuth } from "@octokit/auth-oauth-user";
export type { StrategyOptions, AppAuthOptions, OAuthAppAuthOptions, InstallationAuthOptions, OAuthWebFlowAuthOptions, OAuthDeviceFlowAuthOptions, Authentication, AppAuthentication, OAuthAppAuthentication, InstallationAccessTokenAuthentication, GitHubAppUserAuthentication, GitHubAppUserAuthenticationWithExpiration, } from "./types.js";
export declare function createAppAuth(options: StrategyOptions): AuthInterface;

View File

@@ -0,0 +1 @@
export declare function requiresAppAuth(url: string | undefined): Boolean;

View File

@@ -0,0 +1,2 @@
import type { CacheData, InstallationAccessTokenAuthentication, WithInstallationId } from "./types.js";
export declare function toTokenAuthentication({ installationId, token, createdAt, expiresAt, repositorySelection, permissions, repositoryIds, repositoryNames, singleFileName, }: CacheData & WithInstallationId): InstallationAccessTokenAuthentication;

View File

@@ -0,0 +1,125 @@
import * as OctokitTypes from "@octokit/types";
import { LRUCache } from "lru-cache";
import * as OAuthAppAuth from "@octokit/auth-oauth-app";
type OAuthStrategyOptions = {
clientId?: string;
clientSecret?: string;
};
type CommonStrategyOptions = {
appId: number | string;
privateKey: string;
installationId?: number | string;
request?: OctokitTypes.RequestInterface;
cache?: Cache;
log?: {
warn: (message: string, additionalInfo?: object) => any;
[key: string]: any;
};
};
export type StrategyOptions = OAuthStrategyOptions & CommonStrategyOptions & Record<string, unknown>;
export type AppAuthOptions = {
type: "app";
};
/**
Users SHOULD only enter repositoryIds || repositoryNames.
However, this module still passes both to the backend API to
let the API decide how to handle the logic. We just throw the
response back to the client making the request.
**/
export type InstallationAuthOptions = {
type: "installation";
installationId?: number | string;
repositoryIds?: number[];
repositoryNames?: string[];
permissions?: Permissions;
refresh?: boolean;
factory?: never;
[key: string]: unknown;
};
export type InstallationAuthOptionsWithFactory<T> = {
type: "installation";
installationId?: number | string;
repositoryIds?: number[];
repositoryNames?: string[];
permissions?: Permissions;
refresh?: boolean;
factory: FactoryInstallation<T>;
[key: string]: unknown;
};
export type OAuthAppAuthOptions = OAuthAppAuth.AppAuthOptions;
export type OAuthWebFlowAuthOptions = OAuthAppAuth.WebFlowAuthOptions;
export type OAuthDeviceFlowAuthOptions = OAuthAppAuth.GitHubAppDeviceFlowAuthOptions;
export type Authentication = AppAuthentication | OAuthAppAuthentication | InstallationAccessTokenAuthentication | GitHubAppUserAuthentication | GitHubAppUserAuthenticationWithExpiration;
export type FactoryInstallationOptions = StrategyOptions & Omit<InstallationAuthOptions, "type">;
export interface FactoryInstallation<T> {
(options: FactoryInstallationOptions): T;
}
export interface AuthInterface {
(options: AppAuthOptions): Promise<AppAuthentication>;
(options: OAuthAppAuthOptions): Promise<OAuthAppAuthentication>;
(options: InstallationAuthOptions): Promise<InstallationAccessTokenAuthentication>;
<T = unknown>(options: InstallationAuthOptionsWithFactory<T>): Promise<T>;
(options: OAuthWebFlowAuthOptions): Promise<GitHubAppUserAuthentication | GitHubAppUserAuthenticationWithExpiration>;
(options: OAuthDeviceFlowAuthOptions): Promise<GitHubAppUserAuthentication | GitHubAppUserAuthenticationWithExpiration>;
<T = unknown>(options: OAuthWebFlowAuthOptions & {
factory: OAuthAppAuth.FactoryGitHubWebFlow<T>;
}): Promise<T>;
<T = unknown>(options: OAuthDeviceFlowAuthOptions & {
factory: OAuthAppAuth.FactoryGitHubDeviceFlow<T>;
}): Promise<T>;
hook(request: RequestInterface, route: Route | EndpointOptions, parameters?: RequestParameters): Promise<OctokitTypes.OctokitResponse<any>>;
}
export type AnyResponse = OctokitTypes.OctokitResponse<any>;
export type EndpointDefaults = OctokitTypes.EndpointDefaults;
export type EndpointOptions = OctokitTypes.EndpointOptions;
export type RequestParameters = OctokitTypes.RequestParameters;
export type Route = OctokitTypes.Route;
export type RequestInterface = OctokitTypes.RequestInterface;
export type Cache = LRUCache<string, string> | {
get: (key: string) => string | Promise<string>;
set: (key: string, value: string) => any;
};
export type APP_TYPE = "app";
export type TOKEN_TYPE = "token";
export type INSTALLATION_TOKEN_TYPE = "installation";
export type OAUTH_TOKEN_TYPE = "oauth";
export type REPOSITORY_SELECTION = "all" | "selected";
export type JWT = string;
export type ACCESS_TOKEN = string;
export type UTC_TIMESTAMP = string;
export type AppAuthentication = {
type: APP_TYPE;
token: JWT;
appId: number;
expiresAt: string;
};
export type InstallationAccessTokenData = {
token: ACCESS_TOKEN;
createdAt: UTC_TIMESTAMP;
expiresAt: UTC_TIMESTAMP;
permissions: Permissions;
repositorySelection: REPOSITORY_SELECTION;
repositoryIds?: number[];
repositoryNames?: string[];
singleFileName?: string;
};
export type CacheData = InstallationAccessTokenData;
export type InstallationAccessTokenAuthentication = InstallationAccessTokenData & {
type: TOKEN_TYPE;
tokenType: INSTALLATION_TOKEN_TYPE;
installationId: number;
};
export type OAuthAppAuthentication = OAuthAppAuth.AppAuthentication;
export type GitHubAppUserAuthentication = OAuthAppAuth.GitHubAppUserAuthentication;
export type GitHubAppUserAuthenticationWithExpiration = OAuthAppAuth.GitHubAppUserAuthenticationWithExpiration;
export type FactoryOptions = Required<Omit<StrategyOptions, keyof State>> & State;
export type Permissions = Record<string, string>;
export type WithInstallationId = {
installationId: number;
};
export type State = Required<Omit<CommonStrategyOptions, "installationId">> & {
installationId?: number;
} & OAuthStrategyOptions & {
oauthApp: OAuthAppAuth.GitHubAuthInterface;
};
export {};

View File

@@ -0,0 +1 @@
export declare const VERSION = "6.1.3";

View File

@@ -0,0 +1,56 @@
{
"name": "@octokit/auth-app",
"publishConfig": {
"access": "public",
"provenance": true
},
"version": "6.1.3",
"description": "GitHub App authentication for JavaScript",
"repository": "github:octokit/auth-app.js",
"keywords": [
"github",
"octokit",
"authentication",
"api"
],
"author": "Gregor Martynus (https://github.com/gr2m)",
"license": "MIT",
"dependencies": {
"@octokit/auth-oauth-app": "^7.1.0",
"@octokit/auth-oauth-user": "^4.1.0",
"@octokit/request": "^8.3.1",
"@octokit/request-error": "^5.1.0",
"@octokit/types": "^13.1.0",
"deprecation": "^2.3.1",
"lru-cache": "npm:@wolfy1339/lru-cache@^11.0.2-patch.1",
"universal-github-app-jwt": "^1.1.2",
"universal-user-agent": "^6.0.0"
},
"devDependencies": {
"@octokit/tsconfig": "^2.0.0",
"@sinonjs/fake-timers": "^8.0.0",
"@types/fetch-mock": "^7.3.1",
"@types/jest": "^29.0.0",
"@types/node": "^20.0.0",
"@types/sinonjs__fake-timers": "^8.0.0",
"esbuild": "^0.20.0",
"fetch-mock": "^11.0.0",
"glob": "^10.2.5",
"jest": "^29.0.0",
"prettier": "3.2.5",
"semantic-release-plugin-update-version-in-files": "^1.0.0",
"ts-jest": "^29.0.0",
"typescript": "^5.0.0"
},
"engines": {
"node": ">= 18"
},
"files": [
"dist-*/**",
"bin/**"
],
"main": "dist-node/index.js",
"types": "dist-types/index.d.ts",
"source": "dist-src/index.js",
"sideEffects": false
}

View File

@@ -0,0 +1 @@
../../../@octokit+auth-oauth-app@7.1.0/node_modules/@octokit/auth-oauth-app

View File

@@ -0,0 +1 @@
../../../@octokit+auth-oauth-user@4.1.0/node_modules/@octokit/auth-oauth-user

View File

@@ -0,0 +1 @@
../../../@octokit+request@8.4.0/node_modules/@octokit/request

View File

@@ -0,0 +1 @@
../../../@octokit+request-error@5.1.0/node_modules/@octokit/request-error

View File

@@ -0,0 +1 @@
../../../@octokit+types@13.6.2/node_modules/@octokit/types

View File

@@ -0,0 +1 @@
../../deprecation@2.3.1/node_modules/deprecation

View File

@@ -0,0 +1 @@
../../@wolfy1339+lru-cache@11.0.2-patch.1/node_modules/@wolfy1339/lru-cache

View File

@@ -0,0 +1 @@
../../universal-github-app-jwt@1.2.0/node_modules/universal-github-app-jwt

View File

@@ -0,0 +1 @@
../../universal-user-agent@6.0.1/node_modules/universal-user-agent