Files
codeql-action/node_modules/@octokit/oauth-app/dist-node/index.js
2025-02-19 11:13:12 -08:00

788 lines
23 KiB
JavaScript

// pkg/dist-src/index.js
import { createOAuthAppAuth } from "@octokit/auth-oauth-app";
// pkg/dist-src/version.js
var VERSION = "7.1.6";
// pkg/dist-src/add-event-handler.js
function addEventHandler(state, eventName, eventHandler) {
if (Array.isArray(eventName)) {
for (const singleEventName of eventName) {
addEventHandler(state, singleEventName, eventHandler);
}
return;
}
if (!state.eventHandlers[eventName]) {
state.eventHandlers[eventName] = [];
}
state.eventHandlers[eventName].push(eventHandler);
}
// pkg/dist-src/oauth-app-octokit.js
import { Octokit } from "@octokit/core";
import { getUserAgent } from "universal-user-agent";
var OAuthAppOctokit = Octokit.defaults({
userAgent: `octokit-oauth-app.js/${VERSION} ${getUserAgent()}`
});
// pkg/dist-src/methods/get-user-octokit.js
import { createOAuthUserAuth } from "@octokit/auth-oauth-user";
// pkg/dist-src/emit-event.js
async function emitEvent(state, context) {
const { name, action } = context;
if (state.eventHandlers[`${name}.${action}`]) {
for (const eventHandler of state.eventHandlers[`${name}.${action}`]) {
await eventHandler(context);
}
}
if (state.eventHandlers[name]) {
for (const eventHandler of state.eventHandlers[name]) {
await eventHandler(context);
}
}
}
// pkg/dist-src/methods/get-user-octokit.js
async function getUserOctokitWithState(state, options) {
return state.octokit.auth({
type: "oauth-user",
...options,
async factory(options2) {
const octokit = new state.Octokit({
authStrategy: createOAuthUserAuth,
auth: options2
});
const authentication = await octokit.auth({
type: "get"
});
await emitEvent(state, {
name: "token",
action: "created",
token: authentication.token,
scopes: authentication.scopes,
authentication,
octokit
});
return octokit;
}
});
}
// pkg/dist-src/methods/get-web-flow-authorization-url.js
import * as OAuthMethods from "@octokit/oauth-methods";
function getWebFlowAuthorizationUrlWithState(state, options) {
const optionsWithDefaults = {
clientId: state.clientId,
request: state.octokit.request,
...options,
allowSignup: state.allowSignup ?? options.allowSignup,
redirectUrl: options.redirectUrl ?? state.redirectUrl,
scopes: options.scopes ?? state.defaultScopes
};
return OAuthMethods.getWebFlowAuthorizationUrl({
clientType: state.clientType,
...optionsWithDefaults
});
}
// pkg/dist-src/methods/create-token.js
import * as OAuthAppAuth from "@octokit/auth-oauth-app";
async function createTokenWithState(state, options) {
const authentication = await state.octokit.auth({
type: "oauth-user",
...options
});
await emitEvent(state, {
name: "token",
action: "created",
token: authentication.token,
scopes: authentication.scopes,
authentication,
octokit: new state.Octokit({
authStrategy: OAuthAppAuth.createOAuthUserAuth,
auth: {
clientType: state.clientType,
clientId: state.clientId,
clientSecret: state.clientSecret,
token: authentication.token,
scopes: authentication.scopes,
refreshToken: authentication.refreshToken,
expiresAt: authentication.expiresAt,
refreshTokenExpiresAt: authentication.refreshTokenExpiresAt
}
})
});
return { authentication };
}
// pkg/dist-src/methods/check-token.js
import * as OAuthMethods2 from "@octokit/oauth-methods";
async function checkTokenWithState(state, options) {
const result = await OAuthMethods2.checkToken({
// @ts-expect-error not worth the extra code to appease TS
clientType: state.clientType,
clientId: state.clientId,
clientSecret: state.clientSecret,
request: state.octokit.request,
...options
});
Object.assign(result.authentication, { type: "token", tokenType: "oauth" });
return result;
}
// pkg/dist-src/methods/reset-token.js
import * as OAuthMethods3 from "@octokit/oauth-methods";
import { createOAuthUserAuth as createOAuthUserAuth3 } from "@octokit/auth-oauth-user";
async function resetTokenWithState(state, options) {
const optionsWithDefaults = {
clientId: state.clientId,
clientSecret: state.clientSecret,
request: state.octokit.request,
...options
};
if (state.clientType === "oauth-app") {
const response2 = await OAuthMethods3.resetToken({
clientType: "oauth-app",
...optionsWithDefaults
});
const authentication2 = Object.assign(response2.authentication, {
type: "token",
tokenType: "oauth"
});
await emitEvent(state, {
name: "token",
action: "reset",
token: response2.authentication.token,
scopes: response2.authentication.scopes || void 0,
authentication: authentication2,
octokit: new state.Octokit({
authStrategy: createOAuthUserAuth3,
auth: {
clientType: state.clientType,
clientId: state.clientId,
clientSecret: state.clientSecret,
token: response2.authentication.token,
scopes: response2.authentication.scopes
}
})
});
return { ...response2, authentication: authentication2 };
}
const response = await OAuthMethods3.resetToken({
clientType: "github-app",
...optionsWithDefaults
});
const authentication = Object.assign(response.authentication, {
type: "token",
tokenType: "oauth"
});
await emitEvent(state, {
name: "token",
action: "reset",
token: response.authentication.token,
authentication,
octokit: new state.Octokit({
authStrategy: createOAuthUserAuth3,
auth: {
clientType: state.clientType,
clientId: state.clientId,
clientSecret: state.clientSecret,
token: response.authentication.token
}
})
});
return { ...response, authentication };
}
// pkg/dist-src/methods/refresh-token.js
import * as OAuthMethods4 from "@octokit/oauth-methods";
import { createOAuthUserAuth as createOAuthUserAuth4 } from "@octokit/auth-oauth-user";
async function refreshTokenWithState(state, options) {
if (state.clientType === "oauth-app") {
throw new Error(
"[@octokit/oauth-app] app.refreshToken() is not supported for OAuth Apps"
);
}
const response = await OAuthMethods4.refreshToken({
clientType: "github-app",
clientId: state.clientId,
clientSecret: state.clientSecret,
request: state.octokit.request,
refreshToken: options.refreshToken
});
const authentication = Object.assign(response.authentication, {
type: "token",
tokenType: "oauth"
});
await emitEvent(state, {
name: "token",
action: "refreshed",
token: response.authentication.token,
authentication,
octokit: new state.Octokit({
authStrategy: createOAuthUserAuth4,
auth: {
clientType: state.clientType,
clientId: state.clientId,
clientSecret: state.clientSecret,
token: response.authentication.token
}
})
});
return { ...response, authentication };
}
// pkg/dist-src/methods/scope-token.js
import * as OAuthMethods5 from "@octokit/oauth-methods";
import { createOAuthUserAuth as createOAuthUserAuth5 } from "@octokit/auth-oauth-user";
async function scopeTokenWithState(state, options) {
if (state.clientType === "oauth-app") {
throw new Error(
"[@octokit/oauth-app] app.scopeToken() is not supported for OAuth Apps"
);
}
const response = await OAuthMethods5.scopeToken({
clientType: "github-app",
clientId: state.clientId,
clientSecret: state.clientSecret,
request: state.octokit.request,
...options
});
const authentication = Object.assign(response.authentication, {
type: "token",
tokenType: "oauth"
});
await emitEvent(state, {
name: "token",
action: "scoped",
token: response.authentication.token,
authentication,
octokit: new state.Octokit({
authStrategy: createOAuthUserAuth5,
auth: {
clientType: state.clientType,
clientId: state.clientId,
clientSecret: state.clientSecret,
token: response.authentication.token
}
})
});
return { ...response, authentication };
}
// pkg/dist-src/methods/delete-token.js
import * as OAuthMethods6 from "@octokit/oauth-methods";
import { createUnauthenticatedAuth } from "@octokit/auth-unauthenticated";
async function deleteTokenWithState(state, options) {
const optionsWithDefaults = {
clientId: state.clientId,
clientSecret: state.clientSecret,
request: state.octokit.request,
...options
};
const response = state.clientType === "oauth-app" ? await OAuthMethods6.deleteToken({
clientType: "oauth-app",
...optionsWithDefaults
}) : (
/* v8 ignore next 4 */
await OAuthMethods6.deleteToken({
clientType: "github-app",
...optionsWithDefaults
})
);
await emitEvent(state, {
name: "token",
action: "deleted",
token: options.token,
octokit: new state.Octokit({
authStrategy: createUnauthenticatedAuth,
auth: {
reason: `Handling "token.deleted" event. The access for the token has been revoked.`
}
})
});
return response;
}
// pkg/dist-src/methods/delete-authorization.js
import * as OAuthMethods7 from "@octokit/oauth-methods";
import { createUnauthenticatedAuth as createUnauthenticatedAuth2 } from "@octokit/auth-unauthenticated";
async function deleteAuthorizationWithState(state, options) {
const optionsWithDefaults = {
clientId: state.clientId,
clientSecret: state.clientSecret,
request: state.octokit.request,
...options
};
const response = state.clientType === "oauth-app" ? await OAuthMethods7.deleteAuthorization({
clientType: "oauth-app",
...optionsWithDefaults
}) : (
/* v8 ignore next 4 */
await OAuthMethods7.deleteAuthorization({
clientType: "github-app",
...optionsWithDefaults
})
);
await emitEvent(state, {
name: "token",
action: "deleted",
token: options.token,
octokit: new state.Octokit({
authStrategy: createUnauthenticatedAuth2,
auth: {
reason: `Handling "token.deleted" event. The access for the token has been revoked.`
}
})
});
await emitEvent(state, {
name: "authorization",
action: "deleted",
token: options.token,
octokit: new state.Octokit({
authStrategy: createUnauthenticatedAuth2,
auth: {
reason: `Handling "authorization.deleted" event. The access for the app has been revoked.`
}
})
});
return response;
}
// pkg/dist-src/middleware/unknown-route-response.js
function unknownRouteResponse(request) {
return {
status: 404,
headers: { "content-type": "application/json" },
text: JSON.stringify({
error: `Unknown route: ${request.method} ${request.url}`
})
};
}
// pkg/dist-src/middleware/handle-request.js
async function handleRequest(app, { pathPrefix = "/api/github/oauth" }, request) {
let { pathname } = new URL(request.url, "http://localhost");
if (!pathname.startsWith(`${pathPrefix}/`)) {
return void 0;
}
if (request.method === "OPTIONS") {
return {
status: 200,
headers: {
"access-control-allow-origin": "*",
"access-control-allow-methods": "*",
"access-control-allow-headers": "Content-Type, User-Agent, Authorization"
}
};
}
pathname = pathname.slice(pathPrefix.length + 1);
const route = [request.method, pathname].join(" ");
const routes = {
getLogin: `GET login`,
getCallback: `GET callback`,
createToken: `POST token`,
getToken: `GET token`,
patchToken: `PATCH token`,
patchRefreshToken: `PATCH refresh-token`,
scopeToken: `POST token/scoped`,
deleteToken: `DELETE token`,
deleteGrant: `DELETE grant`
};
if (!Object.values(routes).includes(route)) {
return unknownRouteResponse(request);
}
let json;
try {
const text = await request.text();
json = text ? JSON.parse(text) : {};
} catch (error) {
return {
status: 400,
headers: {
"content-type": "application/json",
"access-control-allow-origin": "*"
},
text: JSON.stringify({
error: "[@octokit/oauth-app] request error"
})
};
}
const { searchParams } = new URL(request.url, "http://localhost");
const query = Object.fromEntries(searchParams);
const headers = request.headers;
try {
if (route === routes.getLogin) {
const authOptions = {};
if (query.state) {
Object.assign(authOptions, { state: query.state });
}
if (query.scopes) {
Object.assign(authOptions, { scopes: query.scopes.split(",") });
}
if (query.allowSignup) {
Object.assign(authOptions, {
allowSignup: query.allowSignup === "true"
});
}
if (query.redirectUrl) {
Object.assign(authOptions, { redirectUrl: query.redirectUrl });
}
const { url } = app.getWebFlowAuthorizationUrl(authOptions);
return { status: 302, headers: { location: url } };
}
if (route === routes.getCallback) {
if (query.error) {
throw new Error(
`[@octokit/oauth-app] ${query.error} ${query.error_description}`
);
}
if (!query.code) {
throw new Error('[@octokit/oauth-app] "code" parameter is required');
}
const {
authentication: { token: token2 }
} = await app.createToken({
code: query.code
});
return {
status: 200,
headers: {
"content-type": "text/html"
},
text: `<h1>Token created successfully</h1>
<p>Your token is: <strong>${token2}</strong>. Copy it now as it cannot be shown again.</p>`
};
}
if (route === routes.createToken) {
const { code, redirectUrl } = json;
if (!code) {
throw new Error('[@octokit/oauth-app] "code" parameter is required');
}
const result = await app.createToken({
code,
redirectUrl
});
delete result.authentication.clientSecret;
return {
status: 201,
headers: {
"content-type": "application/json",
"access-control-allow-origin": "*"
},
text: JSON.stringify(result)
};
}
if (route === routes.getToken) {
const token2 = headers.authorization?.substr("token ".length);
if (!token2) {
throw new Error(
'[@octokit/oauth-app] "Authorization" header is required'
);
}
const result = await app.checkToken({
token: token2
});
delete result.authentication.clientSecret;
return {
status: 200,
headers: {
"content-type": "application/json",
"access-control-allow-origin": "*"
},
text: JSON.stringify(result)
};
}
if (route === routes.patchToken) {
const token2 = headers.authorization?.substr("token ".length);
if (!token2) {
throw new Error(
'[@octokit/oauth-app] "Authorization" header is required'
);
}
const result = await app.resetToken({ token: token2 });
delete result.authentication.clientSecret;
return {
status: 200,
headers: {
"content-type": "application/json",
"access-control-allow-origin": "*"
},
text: JSON.stringify(result)
};
}
if (route === routes.patchRefreshToken) {
const token2 = headers.authorization?.substr("token ".length);
if (!token2) {
throw new Error(
'[@octokit/oauth-app] "Authorization" header is required'
);
}
const { refreshToken: refreshToken2 } = json;
if (!refreshToken2) {
throw new Error(
"[@octokit/oauth-app] refreshToken must be sent in request body"
);
}
const result = await app.refreshToken({ refreshToken: refreshToken2 });
delete result.authentication.clientSecret;
return {
status: 200,
headers: {
"content-type": "application/json",
"access-control-allow-origin": "*"
},
text: JSON.stringify(result)
};
}
if (route === routes.scopeToken) {
const token2 = headers.authorization?.substr("token ".length);
if (!token2) {
throw new Error(
'[@octokit/oauth-app] "Authorization" header is required'
);
}
const result = await app.scopeToken({
token: token2,
...json
});
delete result.authentication.clientSecret;
return {
status: 200,
headers: {
"content-type": "application/json",
"access-control-allow-origin": "*"
},
text: JSON.stringify(result)
};
}
if (route === routes.deleteToken) {
const token2 = headers.authorization?.substr("token ".length);
if (!token2) {
throw new Error(
'[@octokit/oauth-app] "Authorization" header is required'
);
}
await app.deleteToken({
token: token2
});
return {
status: 204,
headers: { "access-control-allow-origin": "*" }
};
}
const token = headers.authorization?.substr("token ".length);
if (!token) {
throw new Error(
'[@octokit/oauth-app] "Authorization" header is required'
);
}
await app.deleteAuthorization({
token
});
return {
status: 204,
headers: { "access-control-allow-origin": "*" }
};
} catch (error) {
return {
status: 400,
headers: {
"content-type": "application/json",
"access-control-allow-origin": "*"
},
text: JSON.stringify({ error: error.message })
};
}
}
// pkg/dist-src/middleware/node/parse-request.js
function parseRequest(request) {
const { method, url, headers } = request;
async function text() {
const text2 = await new Promise((resolve, reject) => {
let bodyChunks = [];
request.on("error", reject).on("data", (chunk) => bodyChunks.push(chunk)).on("end", () => resolve(Buffer.concat(bodyChunks).toString()));
});
return text2;
}
return { method, url, headers, text };
}
// pkg/dist-src/middleware/node/send-response.js
function sendResponse(octokitResponse, response) {
response.writeHead(octokitResponse.status, octokitResponse.headers);
response.end(octokitResponse.text);
}
// pkg/dist-src/middleware/node/index.js
function createNodeMiddleware(app, options = {}) {
return async function(request, response, next) {
const octokitRequest = await parseRequest(request);
const octokitResponse = await handleRequest(app, options, octokitRequest);
if (octokitResponse) {
sendResponse(octokitResponse, response);
return true;
} else {
next?.();
return false;
}
};
}
// pkg/dist-src/middleware/web-worker/parse-request.js
function parseRequest2(request) {
const headers = Object.fromEntries(request.headers.entries());
return {
method: request.method,
url: request.url,
headers,
text: () => request.text()
};
}
// pkg/dist-src/middleware/web-worker/send-response.js
function sendResponse2(octokitResponse) {
const responseOptions = {
status: octokitResponse.status
};
if (octokitResponse.headers) {
Object.assign(responseOptions, { headers: octokitResponse.headers });
}
return new Response(octokitResponse.text, responseOptions);
}
// pkg/dist-src/middleware/web-worker/index.js
function createWebWorkerHandler(app, options = {}) {
return async function(request) {
const octokitRequest = await parseRequest2(request);
const octokitResponse = await handleRequest(app, options, octokitRequest);
return octokitResponse ? sendResponse2(octokitResponse) : void 0;
};
}
// pkg/dist-src/middleware/aws-lambda/api-gateway-v2-parse-request.js
function parseRequest3(request) {
const { method } = request.requestContext.http;
let url = request.rawPath;
const { stage } = request.requestContext;
if (url.startsWith("/" + stage)) url = url.substring(stage.length + 1);
if (request.rawQueryString) url += "?" + request.rawQueryString;
const headers = request.headers;
const text = async () => request.body || "";
return { method, url, headers, text };
}
// pkg/dist-src/middleware/aws-lambda/api-gateway-v2-send-response.js
function sendResponse3(octokitResponse) {
return {
statusCode: octokitResponse.status,
headers: octokitResponse.headers,
body: octokitResponse.text
};
}
// pkg/dist-src/middleware/aws-lambda/api-gateway-v2.js
function createAWSLambdaAPIGatewayV2Handler(app, options = {}) {
return async function(event) {
const request = parseRequest3(event);
const response = await handleRequest(app, options, request);
return response ? sendResponse3(response) : void 0;
};
}
// pkg/dist-src/index.js
var OAuthApp = class {
static VERSION = VERSION;
static defaults(defaults) {
const OAuthAppWithDefaults = class extends this {
constructor(...args) {
super({
...defaults,
...args[0]
});
}
};
return OAuthAppWithDefaults;
}
constructor(options) {
const Octokit2 = options.Octokit || OAuthAppOctokit;
this.type = options.clientType || "oauth-app";
const octokit = new Octokit2({
authStrategy: createOAuthAppAuth,
auth: {
clientType: this.type,
clientId: options.clientId,
clientSecret: options.clientSecret
}
});
const state = {
clientType: this.type,
clientId: options.clientId,
clientSecret: options.clientSecret,
// @ts-expect-error defaultScopes not permitted for GitHub Apps
defaultScopes: options.defaultScopes || [],
allowSignup: options.allowSignup,
baseUrl: options.baseUrl,
redirectUrl: options.redirectUrl,
log: options.log,
Octokit: Octokit2,
octokit,
eventHandlers: {}
};
this.on = addEventHandler.bind(null, state);
this.octokit = octokit;
this.getUserOctokit = getUserOctokitWithState.bind(null, state);
this.getWebFlowAuthorizationUrl = getWebFlowAuthorizationUrlWithState.bind(
null,
state
);
this.createToken = createTokenWithState.bind(
null,
state
);
this.checkToken = checkTokenWithState.bind(
null,
state
);
this.resetToken = resetTokenWithState.bind(
null,
state
);
this.refreshToken = refreshTokenWithState.bind(
null,
state
);
this.scopeToken = scopeTokenWithState.bind(
null,
state
);
this.deleteToken = deleteTokenWithState.bind(null, state);
this.deleteAuthorization = deleteAuthorizationWithState.bind(null, state);
}
// assigned during constructor
type;
on;
octokit;
getUserOctokit;
getWebFlowAuthorizationUrl;
createToken;
checkToken;
resetToken;
refreshToken;
scopeToken;
deleteToken;
deleteAuthorization;
};
export {
OAuthApp,
createAWSLambdaAPIGatewayV2Handler,
createNodeMiddleware,
createWebWorkerHandler,
handleRequest,
sendResponse as sendNodeResponse,
unknownRouteResponse
};