Socket
Socket
Sign inDemoInstall

@octokit/oauth-app

Package Overview
Dependencies
Maintainers
2
Versions
67
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@octokit/oauth-app - npm Package Compare versions

Comparing version 2.1.0 to 3.0.0

dist-src/methods/get-user-octokit.js

570

dist-node/index.js

@@ -7,12 +7,11 @@ 'use strict';

var authOauthApp = require('@octokit/auth-oauth-app');
var OAuthAppAuth = require('@octokit/auth-oauth-app');
var core = require('@octokit/core');
var universalUserAgent = require('universal-user-agent');
var oauthAuthorizationUrl = require('@octokit/oauth-authorization-url');
var request = require('@octokit/request');
var btoa = _interopDefault(require('btoa-lite'));
var authOauthUser = require('@octokit/auth-oauth-user');
var OAuthMethods = require('@octokit/oauth-methods');
var authUnauthenticated = require('@octokit/auth-unauthenticated');
var fromEntries = _interopDefault(require('fromentries'));
const VERSION = "2.1.0";
const VERSION = "3.0.0";

@@ -88,71 +87,28 @@ function addEventHandler(state, eventName, eventHandler) {

function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose(source, excluded);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
async function getUserOctokitWithState(state, options) {
return state.octokit.auth(_objectSpread2(_objectSpread2({
type: "oauth-user"
}, options), {}, {
factory(options) {
return new state.Octokit({
authStrategy: authOauthUser.createOAuthUserAuth,
auth: options
});
}
}
return target;
}));
}
function getAuthorizationUrl(options) {
const {
url
} = oauthAuthorizationUrl.oauthAuthorizationUrl(options);
return url;
}
function getAuthorizationUrlWithState(state, options) {
const {
clientId = state.clientId,
allowSignup = state.allowSignup,
baseUrl = state.baseUrl,
scopes = state.defaultScopes,
// TODO: https://github.com/octokit/oauth-app.js/pull/203#issuecomment-799683991
clientType = /^lv1\./.test(clientId) ? "github-app" : "oauth-app"
} = options,
otherOptions = _objectWithoutProperties(options, ["clientId", "allowSignup", "baseUrl", "scopes", "clientType"]);
function getWebFlowAuthorizationUrlWithState(state, options) {
const optionsWithDefaults = _objectSpread2(_objectSpread2({
clientId: state.clientId,
request: state.octokit.request
}, options), {}, {
allowSignup: options.allowSignup || state.allowSignup,
scopes: options.scopes || state.defaultScopes
});
if (clientType === "oauth-app") {
return getAuthorizationUrl(_objectSpread2(_objectSpread2({}, otherOptions), {}, {
clientType: "oauth-app",
clientId,
allowSignup,
baseUrl,
scopes
}));
}
return getAuthorizationUrl(_objectSpread2(_objectSpread2({}, otherOptions), {}, {
clientType: "github-app",
clientId,
allowSignup,
baseUrl
}));
return OAuthMethods.getWebFlowAuthorizationUrl(_objectSpread2({
clientType: state.clientType
}, optionsWithDefaults));
}

@@ -179,148 +135,177 @@

async function createTokenWithAuth(auth, options) {
// @ts-ignore fix return types for auth()
const {
token,
scopes
} = await auth({
type: "token",
state: options.state,
code: options.code
});
return {
token,
scopes
};
}
function createToken(options) {
const {
clientId,
clientSecret
} = options,
otherOptions = _objectWithoutProperties(options, ["clientId", "clientSecret"]);
const auth = authOauthApp.createOAuthAppAuth({
clientId,
clientSecret
});
return createTokenWithAuth(auth, otherOptions);
}
async function createTokenWithState(state, options) {
const result = await createTokenWithAuth(state.octokit.auth, options);
const authentication = await state.octokit.auth(_objectSpread2({
type: "oauth-user"
}, options));
await emitEvent(state, {
name: "token",
action: "created",
token: result.token,
scopes: result.scopes,
get octokit() {
return new state.Octokit({
auth: result.token
});
}
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 result;
return {
authentication
};
}
async function sendCheckTokenRequest(request, options) {
const {
data
} = await request("POST /applications/{client_id}/token", options);
return data;
async function checkTokenWithState(state, options) {
return await OAuthMethods.checkToken(_objectSpread2({
// @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));
}
async function checkToken(options) {
const request$1 = request.request.defaults({
headers: {
authorization: `basic ${btoa(`${options.clientId}:${options.clientSecret}`)}`
}
});
return sendCheckTokenRequest(request$1, {
client_id: options.clientId,
access_token: options.token
});
}
function checkTokenWithState(state, options) {
return sendCheckTokenRequest(state.octokit.request, {
client_id: state.clientId,
access_token: options.token
});
}
async function resetTokenWithState(state, options) {
const optionsWithDefaults = _objectSpread2({
clientId: state.clientId,
clientSecret: state.clientSecret,
request: state.octokit.request
}, options);
async function sendResetTokenRequest(request, options) {
const {
data
} = await request("PATCH /applications/{client_id}/token", options);
return data;
}
if (state.clientType === "oauth-app") {
const response = await OAuthMethods.resetToken(_objectSpread2({
clientType: "oauth-app"
}, optionsWithDefaults));
await emitEvent(state, {
name: "token",
action: "reset",
token: response.authentication.token,
scopes: response.authentication.scopes || undefined,
authentication: _objectSpread2({
type: "token",
tokenType: "oauth"
}, response.authentication),
octokit: new state.Octokit({
authStrategy: authOauthUser.createOAuthUserAuth,
auth: {
clientType: state.clientType,
clientId: state.clientId,
clientSecret: state.clientSecret,
token: response.authentication.token,
scopes: response.authentication.scopes
}
})
});
return response;
}
function resetToken(options) {
const request$1 = request.request.defaults({
headers: {
authorization: `basic ${btoa(`${options.clientId}:${options.clientSecret}`)}`
}
});
return sendResetTokenRequest(request$1, {
client_id: options.clientId,
access_token: options.token
});
}
async function resetTokenWithState(state, options) {
const result = await sendResetTokenRequest(state.octokit.request, {
client_id: state.clientId,
access_token: options.token
});
const response = await OAuthMethods.resetToken(_objectSpread2({
clientType: "github-app"
}, optionsWithDefaults));
await emitEvent(state, {
name: "token",
action: "reset",
token: result.token,
scopes: result.scopes || undefined,
get octokit() {
return new state.Octokit({
auth: result.token
});
}
token: response.authentication.token,
authentication: _objectSpread2({
type: "token",
tokenType: "oauth"
}, response.authentication),
octokit: new state.Octokit({
authStrategy: authOauthUser.createOAuthUserAuth,
auth: {
clientType: state.clientType,
clientId: state.clientId,
clientSecret: state.clientSecret,
token: response.authentication.token
}
})
});
return result;
return response;
}
async function sendDeleteTokenRequest(request, options) {
const {
data
} = await request("DELETE /applications/{client_id}/token", options);
return data;
}
async function refreshTokenWithState(state, options) {
if (state.clientType === "oauth-app") {
throw new Error("[@octokit/oauth-app] app.refreshToken() is not supported for OAuth Apps");
}
function deleteToken(options) {
const request$1 = request.request.defaults({
headers: {
authorization: `basic ${btoa(`${options.clientId}:${options.clientSecret}`)}`
}
const response = await OAuthMethods.refreshToken({
clientType: "github-app",
clientId: state.clientId,
clientSecret: state.clientSecret,
request: state.octokit.request,
refreshToken: options.refreshToken
});
return sendDeleteTokenRequest(request$1, {
client_id: options.clientId,
access_token: options.token
await emitEvent(state, {
name: "token",
action: "refreshed",
token: response.authentication.token,
authentication: _objectSpread2({
type: "token",
tokenType: "oauth"
}, response.authentication),
octokit: new state.Octokit({
authStrategy: authOauthUser.createOAuthUserAuth,
auth: {
clientType: state.clientType,
clientId: state.clientId,
clientSecret: state.clientSecret,
token: response.authentication.token
}
})
});
return response;
}
async function deleteTokenWithState(state, options) {
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 OAuthMethods.scopeToken(_objectSpread2({
clientType: "github-app",
clientId: state.clientId,
clientSecret: state.clientSecret,
request: state.octokit.request
}, options));
await emitEvent(state, {
name: "token",
action: "before_deleted",
token: options.token,
action: "scoped",
token: response.authentication.token,
authentication: _objectSpread2({
type: "token",
tokenType: "oauth"
}, response.authentication),
octokit: new state.Octokit({
authStrategy: authOauthUser.createOAuthUserAuth,
auth: {
clientType: state.clientType,
clientId: state.clientId,
clientSecret: state.clientSecret,
token: response.authentication.token
}
})
});
return response;
}
get octokit() {
return new state.Octokit({
auth: options.token
});
}
async function deleteTokenWithState(state, options) {
const optionsWithDefaults = _objectSpread2({
clientId: state.clientId,
clientSecret: state.clientSecret,
request: state.octokit.request
}, options);
});
const result = await sendDeleteTokenRequest(state.octokit.request, {
client_id: state.clientId,
access_token: options.token
});
const response = state.clientType === "oauth-app" ? await OAuthMethods.deleteToken(_objectSpread2({
clientType: "oauth-app"
}, optionsWithDefaults)) : // istanbul ignore next
await OAuthMethods.deleteToken(_objectSpread2({
clientType: "github-app"
}, optionsWithDefaults));
await emitEvent(state, {

@@ -330,80 +315,35 @@ name: "token",

token: options.token,
get octokit() {
return new state.Octokit({
authStrategy: authUnauthenticated.createUnauthenticatedAuth,
auth: {
reason: `Handling "token.deleted" event. The access for the token has been revoked.`
}
});
}
octokit: new state.Octokit({
authStrategy: authUnauthenticated.createUnauthenticatedAuth,
auth: {
reason: `Handling "token.deleted" event. The access for the token has been revoked.`
}
})
});
return result;
return response;
}
async function sendDeleteAuthorizationRequest(request, options) {
const {
data
} = await request("DELETE /applications/{client_id}/grant", options);
return data;
}
function deleteAuthorization(options) {
const request$1 = request.request.defaults({
request: {
hook: authOauthApp.createOAuthAppAuth({
clientId: options.clientId,
clientSecret: options.clientSecret
}).hook
}
});
return sendDeleteAuthorizationRequest(request$1, {
client_id: options.clientId,
access_token: options.token
});
}
async function deleteAuthorizationWithState(state, options) {
await emitEvent(state, {
name: "authorization",
action: "before_deleted",
token: options.token,
const optionsWithDefaults = _objectSpread2({
clientId: state.clientId,
clientSecret: state.clientSecret,
request: state.octokit.request
}, options);
get octokit() {
return new state.Octokit({
auth: options.token
});
}
});
const response = state.clientType === "oauth-app" ? await OAuthMethods.deleteAuthorization(_objectSpread2({
clientType: "oauth-app"
}, optionsWithDefaults)) : // istanbul ignore next
await OAuthMethods.deleteAuthorization(_objectSpread2({
clientType: "github-app"
}, optionsWithDefaults));
await emitEvent(state, {
name: "token",
action: "before_deleted",
token: options.token,
get octokit() {
return new state.Octokit({
auth: options.token
});
}
});
const result = await sendDeleteAuthorizationRequest(state.octokit.request, {
client_id: state.clientId,
access_token: options.token
});
await emitEvent(state, {
name: "token",
action: "deleted",
token: options.token,
get octokit() {
return new state.Octokit({
authStrategy: authUnauthenticated.createUnauthenticatedAuth,
auth: {
reason: `Handling "token.deleted" event. The access for the token has been revoked.`
}
});
}
octokit: new state.Octokit({
authStrategy: authUnauthenticated.createUnauthenticatedAuth,
auth: {
reason: `Handling "token.deleted" event. The access for the token has been revoked.`
}
})
});

@@ -414,14 +354,10 @@ await emitEvent(state, {

token: options.token,
get octokit() {
return new state.Octokit({
authStrategy: authUnauthenticated.createUnauthenticatedAuth,
auth: {
reason: `Handling "authorization.deleted" event. The access for the app has been revoked.`
}
});
}
octokit: new state.Octokit({
authStrategy: authUnauthenticated.createUnauthenticatedAuth,
auth: {
reason: `Handling "authorization.deleted" event. The access for the app has been revoked.`
}
})
});
return result;
return response;
}

@@ -479,2 +415,4 @@

patchToken: `PATCH ${options.pathPrefix}/token`,
patchRefreshToken: `PATCH ${options.pathPrefix}/refresh-token`,
scopeToken: `POST ${options.pathPrefix}/token/scoped`,
deleteToken: `DELETE ${options.pathPrefix}/token`,

@@ -505,7 +443,7 @@ deleteGrant: `DELETE ${options.pathPrefix}/grant`

query,
body
body = {}
} = parsedRequest;
try {
var _headers$authorizatio4;
var _headers$authorizatio6;

@@ -515,3 +453,5 @@ if (route === routes.getLogin) {

const url = app.getAuthorizationUrl({
const {
url
} = app.getWebFlowAuthorizationUrl({
state: query.state,

@@ -538,3 +478,5 @@ scopes: (_query$scopes = query.scopes) === null || _query$scopes === void 0 ? void 0 : _query$scopes.split(","),

const {
token
authentication: {
token
}
} = await app.createToken({

@@ -554,3 +496,2 @@ state: query.state,

if (route === routes.createToken) {
// @ts-ignore body is guaraenteed to exist
const {

@@ -567,7 +508,10 @@ state: oauthState,

const {
token,
scopes
authentication: {
token,
scopes
}
} = await app.createToken({
state: oauthState,
code
code,
redirectUrl
});

@@ -619,3 +563,3 @@ response.writeHead(201, {

if (route === routes.deleteToken) {
if (route === routes.patchRefreshToken) {
var _headers$authorizatio3;

@@ -629,2 +573,46 @@

const {
refreshToken
} = body;
if (!refreshToken) {
throw new Error("[@octokit/oauth-app] refreshToken must be sent in request body");
}
const result = await app.refreshToken({
refreshToken
});
response.writeHead(200, {
"content-type": "application/json"
});
return response.end(JSON.stringify(result));
}
if (route === routes.scopeToken) {
var _headers$authorizatio4;
const token = (_headers$authorizatio4 = headers.authorization) === null || _headers$authorizatio4 === void 0 ? void 0 : _headers$authorizatio4.substr("token ".length);
if (!token) {
throw new Error('[@octokit/oauth-app] "Authorization" header is required');
}
const result = await app.scopeToken(_objectSpread2({
token
}, body));
response.writeHead(200, {
"content-type": "application/json"
});
return response.end(JSON.stringify(result));
}
if (route === routes.deleteToken) {
var _headers$authorizatio5;
const token = (_headers$authorizatio5 = headers.authorization) === null || _headers$authorizatio5 === void 0 ? void 0 : _headers$authorizatio5.substr("token ".length);
if (!token) {
throw new Error('[@octokit/oauth-app] "Authorization" header is required');
}
await app.deleteToken({

@@ -638,3 +626,3 @@ token

const token = (_headers$authorizatio4 = headers.authorization) === null || _headers$authorizatio4 === void 0 ? void 0 : _headers$authorizatio4.substr("token ".length);
const token = (_headers$authorizatio6 = headers.authorization) === null || _headers$authorizatio6 === void 0 ? void 0 : _headers$authorizatio6.substr("token ".length);

@@ -679,12 +667,10 @@ if (!token) {

function getNodeMiddleware(app, options) {
console.warn(`[@octokit/oauth-app] getNodeMiddleWare() is deprecated. Use createNodeMiddleware() instead`);
return createNodeMiddleware(app, options);
}
class OAuthApp {
constructor(options) {
const Octokit = options.Octokit || OAuthAppOctokit;
this.type = options.clientType || "oauth-app";
const octokit = new Octokit({
authStrategy: authOauthApp.createOAuthAppAuth,
authStrategy: OAuthAppAuth.createOAuthAppAuth,
auth: {
clientType: this.type,
clientId: options.clientId,

@@ -695,4 +681,6 @@ 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 || [],

@@ -708,6 +696,9 @@ allowSignup: options.allowSignup,

this.octokit = octokit;
this.getAuthorizationUrl = getAuthorizationUrlWithState.bind(null, state);
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);

@@ -721,10 +712,3 @@ this.deleteAuthorization = deleteAuthorizationWithState.bind(null, state);

exports.OAuthApp = OAuthApp;
exports.checkToken = checkToken;
exports.createNodeMiddleware = createNodeMiddleware;
exports.createToken = createToken;
exports.deleteAuthorization = deleteAuthorization;
exports.deleteToken = deleteToken;
exports.getAuthorizationUrl = getAuthorizationUrl;
exports.getNodeMiddleware = getNodeMiddleware;
exports.resetToken = resetToken;
//# sourceMappingURL=index.js.map

@@ -5,26 +5,20 @@ import { createOAuthAppAuth } from "@octokit/auth-oauth-app";

import { OAuthAppOctokit } from "./oauth-app-octokit";
import { getAuthorizationUrlWithState, } from "./methods/get-authorization-url";
import { createTokenWithState } from "./methods/create-token";
import { checkTokenWithState } from "./methods/check-token";
import { resetTokenWithState } from "./methods/reset-token";
import { deleteTokenWithState } from "./methods/delete-token";
import { getUserOctokitWithState, } from "./methods/get-user-octokit";
import { getWebFlowAuthorizationUrlWithState, } from "./methods/get-web-flow-authorization-url";
import { createTokenWithState, } from "./methods/create-token";
import { checkTokenWithState, } from "./methods/check-token";
import { resetTokenWithState, } from "./methods/reset-token";
import { refreshTokenWithState, } from "./methods/refresh-token";
import { scopeTokenWithState, } from "./methods/scope-token";
import { deleteTokenWithState, } from "./methods/delete-token";
import { deleteAuthorizationWithState, } from "./methods/delete-authorization";
import { createNodeMiddleware } from "./middleware/node/index";
export { getAuthorizationUrl } from "./methods/get-authorization-url";
export { createToken } from "./methods/create-token";
export { checkToken } from "./methods/check-token";
export { resetToken } from "./methods/reset-token";
export { deleteToken } from "./methods/delete-token";
export { deleteAuthorization } from "./methods/delete-authorization";
export { createNodeMiddleware } from "./middleware/node/index";
export function getNodeMiddleware(app, options) {
console.warn(`[@octokit/oauth-app] getNodeMiddleWare() is deprecated. Use createNodeMiddleware() instead`);
return createNodeMiddleware(app, options);
}
export class OAuthApp {
constructor(options) {
const Octokit = options.Octokit || OAuthAppOctokit;
this.type = (options.clientType || "oauth-app");
const octokit = new Octokit({
authStrategy: createOAuthAppAuth,
auth: {
clientType: this.type,
clientId: options.clientId,

@@ -35,4 +29,6 @@ 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 || [],

@@ -48,6 +44,9 @@ allowSignup: options.allowSignup,

this.octokit = octokit;
this.getAuthorizationUrl = getAuthorizationUrlWithState.bind(null, state);
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);

@@ -54,0 +53,0 @@ this.deleteAuthorization = deleteAuthorizationWithState.bind(null, state);

@@ -1,23 +0,11 @@

import { request as defaultRequest } from "@octokit/request";
import btoa from "btoa-lite";
async function sendCheckTokenRequest(request, options) {
const { data } = await request("POST /applications/{client_id}/token", options);
return data;
}
export async function checkToken(options) {
const request = defaultRequest.defaults({
headers: {
authorization: `basic ${btoa(`${options.clientId}:${options.clientSecret}`)}`,
},
import * as OAuthMethods from "@octokit/oauth-methods";
export async function checkTokenWithState(state, options) {
return await OAuthMethods.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,
});
return sendCheckTokenRequest(request, {
client_id: options.clientId,
access_token: options.token,
});
}
export function checkTokenWithState(state, options) {
return sendCheckTokenRequest(state.octokit.request, {
client_id: state.clientId,
access_token: options.token,
});
}

@@ -1,32 +0,29 @@

import { createOAuthAppAuth } from "@octokit/auth-oauth-app";
import * as OAuthAppAuth from "@octokit/auth-oauth-app";
import { emitEvent } from "../emit-event";
async function createTokenWithAuth(auth, options) {
// @ts-ignore fix return types for auth()
const { token, scopes } = await auth({
type: "token",
state: options.state,
code: options.code,
export async function createTokenWithState(state, options) {
const authentication = await state.octokit.auth({
type: "oauth-user",
...options,
});
return { token, scopes };
}
export function createToken(options) {
const { clientId, clientSecret, ...otherOptions } = options;
const auth = createOAuthAppAuth({
clientId,
clientSecret,
});
return createTokenWithAuth(auth, otherOptions);
}
export async function createTokenWithState(state, options) {
const result = await createTokenWithAuth(state.octokit.auth, options);
await emitEvent(state, {
name: "token",
action: "created",
token: result.token,
scopes: result.scopes,
get octokit() {
return new state.Octokit({ auth: result.token });
},
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 result;
return { authentication };
}

@@ -1,56 +0,31 @@

import { createOAuthAppAuth } from "@octokit/auth-oauth-app";
import * as OAuthMethods from "@octokit/oauth-methods";
import { createUnauthenticatedAuth } from "@octokit/auth-unauthenticated";
import { request as defaultRequest } from "@octokit/request";
import { emitEvent } from "../emit-event";
async function sendDeleteAuthorizationRequest(request, options) {
const { data } = await request("DELETE /applications/{client_id}/grant", options);
return data;
}
export function deleteAuthorization(options) {
const request = defaultRequest.defaults({
request: {
hook: createOAuthAppAuth({
clientId: options.clientId,
clientSecret: options.clientSecret,
}).hook,
},
});
return sendDeleteAuthorizationRequest(request, {
client_id: options.clientId,
access_token: options.token,
});
}
export 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 OAuthMethods.deleteAuthorization({
clientType: "oauth-app",
...optionsWithDefaults,
})
: // istanbul ignore next
await OAuthMethods.deleteAuthorization({
clientType: "github-app",
...optionsWithDefaults,
});
await emitEvent(state, {
name: "authorization",
action: "before_deleted",
token: options.token,
get octokit() {
return new state.Octokit({ auth: options.token });
},
});
await emitEvent(state, {
name: "token",
action: "before_deleted",
token: options.token,
get octokit() {
return new state.Octokit({ auth: options.token });
},
});
const result = await sendDeleteAuthorizationRequest(state.octokit.request, {
client_id: state.clientId,
access_token: options.token,
});
await emitEvent(state, {
name: "token",
action: "deleted",
token: options.token,
get octokit() {
return new state.Octokit({
authStrategy: createUnauthenticatedAuth,
auth: {
reason: `Handling "token.deleted" event. The access for the token has been revoked.`,
},
});
},
octokit: new state.Octokit({
authStrategy: createUnauthenticatedAuth,
auth: {
reason: `Handling "token.deleted" event. The access for the token has been revoked.`,
},
}),
});

@@ -61,12 +36,10 @@ await emitEvent(state, {

token: options.token,
get octokit() {
return new state.Octokit({
authStrategy: createUnauthenticatedAuth,
auth: {
reason: `Handling "authorization.deleted" event. The access for the app has been revoked.`,
},
});
},
octokit: new state.Octokit({
authStrategy: createUnauthenticatedAuth,
auth: {
reason: `Handling "authorization.deleted" event. The access for the app has been revoked.`,
},
}),
});
return result;
return response;
}

@@ -1,47 +0,33 @@

import { request as defaultRequest } from "@octokit/request";
import * as OAuthMethods from "@octokit/oauth-methods";
import { createUnauthenticatedAuth } from "@octokit/auth-unauthenticated";
import btoa from "btoa-lite";
import { emitEvent } from "../emit-event";
async function sendDeleteTokenRequest(request, options) {
const { data } = await request("DELETE /applications/{client_id}/token", options);
return data;
}
export function deleteToken(options) {
const request = defaultRequest.defaults({
headers: {
authorization: `basic ${btoa(`${options.clientId}:${options.clientSecret}`)}`,
},
});
return sendDeleteTokenRequest(request, {
client_id: options.clientId,
access_token: options.token,
});
}
export 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 OAuthMethods.deleteToken({
clientType: "oauth-app",
...optionsWithDefaults,
})
: // istanbul ignore next
await OAuthMethods.deleteToken({
clientType: "github-app",
...optionsWithDefaults,
});
await emitEvent(state, {
name: "token",
action: "before_deleted",
token: options.token,
get octokit() {
return new state.Octokit({ auth: options.token });
},
});
const result = await sendDeleteTokenRequest(state.octokit.request, {
client_id: state.clientId,
access_token: options.token,
});
await emitEvent(state, {
name: "token",
action: "deleted",
token: options.token,
get octokit() {
return new state.Octokit({
authStrategy: createUnauthenticatedAuth,
auth: {
reason: `Handling "token.deleted" event. The access for the token has been revoked.`,
},
});
},
octokit: new state.Octokit({
authStrategy: createUnauthenticatedAuth,
auth: {
reason: `Handling "token.deleted" event. The access for the token has been revoked.`,
},
}),
});
return result;
return response;
}

@@ -1,23 +0,42 @@

import { request as defaultRequest } from "@octokit/request";
import btoa from "btoa-lite";
import * as OAuthMethods from "@octokit/oauth-methods";
import { emitEvent } from "../emit-event";
async function sendResetTokenRequest(request, options) {
const { data } = await request("PATCH /applications/{client_id}/token", options);
return data;
}
export function resetToken(options) {
const request = defaultRequest.defaults({
headers: {
authorization: `basic ${btoa(`${options.clientId}:${options.clientSecret}`)}`,
},
});
return sendResetTokenRequest(request, {
client_id: options.clientId,
access_token: options.token,
});
}
import { createOAuthUserAuth } from "@octokit/auth-oauth-user";
export async function resetTokenWithState(state, options) {
const result = await sendResetTokenRequest(state.octokit.request, {
client_id: state.clientId,
access_token: options.token,
const optionsWithDefaults = {
clientId: state.clientId,
clientSecret: state.clientSecret,
request: state.octokit.request,
...options,
};
if (state.clientType === "oauth-app") {
const response = await OAuthMethods.resetToken({
clientType: "oauth-app",
...optionsWithDefaults,
});
await emitEvent(state, {
name: "token",
action: "reset",
token: response.authentication.token,
scopes: response.authentication.scopes || undefined,
authentication: {
type: "token",
tokenType: "oauth",
...response.authentication,
},
octokit: new state.Octokit({
authStrategy: createOAuthUserAuth,
auth: {
clientType: state.clientType,
clientId: state.clientId,
clientSecret: state.clientSecret,
token: response.authentication.token,
scopes: response.authentication.scopes,
},
}),
});
return response;
}
const response = await OAuthMethods.resetToken({
clientType: "github-app",
...optionsWithDefaults,
});

@@ -27,11 +46,19 @@ await emitEvent(state, {

action: "reset",
token: result.token,
scopes: result.scopes || undefined,
get octokit() {
return new state.Octokit({
auth: result.token,
});
token: response.authentication.token,
authentication: {
type: "token",
tokenType: "oauth",
...response.authentication,
},
octokit: new state.Octokit({
authStrategy: createOAuthUserAuth,
auth: {
clientType: state.clientType,
clientId: state.clientId,
clientSecret: state.clientSecret,
token: response.authentication.token,
},
}),
});
return result;
return response;
}

@@ -13,2 +13,4 @@ import { parseRequest } from "./parse-request";

patchToken: `PATCH ${options.pathPrefix}/token`,
patchRefreshToken: `PATCH ${options.pathPrefix}/refresh-token`,
scopeToken: `POST ${options.pathPrefix}/token/scoped`,
deleteToken: `DELETE ${options.pathPrefix}/token`,

@@ -33,6 +35,6 @@ deleteGrant: `DELETE ${options.pathPrefix}/grant`,

}
const { headers, query, body } = parsedRequest;
const { headers, query, body = {} } = parsedRequest;
try {
if (route === routes.getLogin) {
const url = app.getAuthorizationUrl({
const { url } = app.getWebFlowAuthorizationUrl({
state: query.state,

@@ -53,3 +55,3 @@ scopes: query.scopes?.split(","),

}
const { token } = await app.createToken({
const { authentication: { token }, } = await app.createToken({
state: query.state,

@@ -67,3 +69,2 @@ code: query.code,

if (route === routes.createToken) {
// @ts-ignore body is guaraenteed to exist
const { state: oauthState, code, redirectUrl } = body;

@@ -73,5 +74,6 @@ if (!oauthState || !code) {

}
const { token, scopes } = await app.createToken({
const { authentication: { token, scopes }, } = await app.createToken({
state: oauthState,
code,
redirectUrl,
});

@@ -109,2 +111,31 @@ response.writeHead(201, {

}
if (route === routes.patchRefreshToken) {
const token = headers.authorization?.substr("token ".length);
if (!token) {
throw new Error('[@octokit/oauth-app] "Authorization" header is required');
}
const { refreshToken } = body;
if (!refreshToken) {
throw new Error("[@octokit/oauth-app] refreshToken must be sent in request body");
}
const result = await app.refreshToken({ refreshToken });
response.writeHead(200, {
"content-type": "application/json",
});
return response.end(JSON.stringify(result));
}
if (route === routes.scopeToken) {
const token = headers.authorization?.substr("token ".length);
if (!token) {
throw new Error('[@octokit/oauth-app] "Authorization" header is required');
}
const result = await app.scopeToken({
token,
...body,
});
response.writeHead(200, {
"content-type": "application/json",
});
return response.end(JSON.stringify(result));
}
if (route === routes.deleteToken) {

@@ -111,0 +142,0 @@ const token = headers.authorization?.substr("token ".length);

@@ -1,1 +0,1 @@

export const VERSION = "2.1.0";
export const VERSION = "3.0.0";

@@ -1,2 +0,2 @@

import { EventHandler, EventAndActionName, State } from "./types";
export declare function addEventHandler(state: State, eventName: EventAndActionName | EventAndActionName[], eventHandler: EventHandler): void;
import { EventHandler, EventAndActionName, State, ClientType } from "./types";
export declare function addEventHandler(state: State, eventName: EventAndActionName | EventAndActionName[], eventHandler: EventHandler<ClientType>): void;

@@ -1,2 +0,2 @@

import { State, EventHandlerContext } from "./types";
export declare function emitEvent(state: State, context: EventHandlerContext): Promise<void>;
import { State, EventHandlerContext, ClientType } from "./types";
export declare function emitEvent(state: State, context: EventHandlerContext<ClientType>): Promise<void>;

@@ -1,29 +0,27 @@

/// <reference types="node" />
import { AppGetAuthorizationUrl } from "./methods/get-authorization-url";
import { AppCreateToken } from "./methods/create-token";
import { AppCheckToken } from "./methods/check-token";
import { AppResetToken } from "./methods/reset-token";
import { AppDeleteToken } from "./methods/delete-token";
import { AppDeleteAuthorization } from "./methods/delete-authorization";
import { ConstructorOptions, OctokitInstance, AddEventHandler } from "./types";
import { MiddlewareOptions } from "./middleware/node/types";
export { getAuthorizationUrl } from "./methods/get-authorization-url";
export { createToken } from "./methods/create-token";
export { checkToken } from "./methods/check-token";
export { resetToken } from "./methods/reset-token";
export { deleteToken } from "./methods/delete-token";
export { deleteAuthorization } from "./methods/delete-authorization";
import { GetUserOctokitWithStateInterface } from "./methods/get-user-octokit";
import { GetWebFlowAuthorizationUrlInterface } from "./methods/get-web-flow-authorization-url";
import { CreateTokenInterface } from "./methods/create-token";
import { CheckTokenInterface } from "./methods/check-token";
import { ResetTokenInterface } from "./methods/reset-token";
import { RefreshTokenInterface } from "./methods/refresh-token";
import { ScopeTokenInterface } from "./methods/scope-token";
import { DeleteTokenInterface } from "./methods/delete-token";
import { DeleteAuthorizationInterface } from "./methods/delete-authorization";
import { ConstructorOptions, OctokitInstance, ClientType, AddEventHandler } from "./types";
export { createNodeMiddleware } from "./middleware/node/index";
export declare function getNodeMiddleware(app: OAuthApp, options?: MiddlewareOptions): (request: import("http").IncomingMessage, response: import("http").ServerResponse) => Promise<void>;
export declare class OAuthApp {
export declare class OAuthApp<TClientType extends ClientType = "oauth-app"> {
static VERSION: string;
constructor(options: ConstructorOptions);
on: AddEventHandler;
constructor(options: ConstructorOptions<TClientType>);
type: TClientType;
on: AddEventHandler<TClientType>;
octokit: OctokitInstance;
getAuthorizationUrl: AppGetAuthorizationUrl;
createToken: AppCreateToken;
checkToken: AppCheckToken;
resetToken: AppResetToken;
deleteToken: AppDeleteToken;
deleteAuthorization: AppDeleteAuthorization;
getUserOctokit: GetUserOctokitWithStateInterface<TClientType>;
getWebFlowAuthorizationUrl: GetWebFlowAuthorizationUrlInterface<TClientType>;
createToken: CreateTokenInterface<TClientType>;
checkToken: CheckTokenInterface<TClientType>;
resetToken: ResetTokenInterface<TClientType>;
refreshToken: RefreshTokenInterface;
scopeToken: ScopeTokenInterface;
deleteToken: DeleteTokenInterface;
deleteAuthorization: DeleteAuthorizationInterface;
}

@@ -1,209 +0,9 @@

import { State } from "../types";
declare type Options = {
clientId: string;
clientSecret: string;
import * as OAuthMethods from "@octokit/oauth-methods";
import { ClientType, State } from "../types";
export declare type CheckTokenOptions = {
token: string;
};
declare type StateOptions = {
token: string;
};
export declare function checkToken(options: Options): Promise<{
id: number;
url: string;
scopes: string[] | null;
token: string;
token_last_eight: string | null;
hashed_token: string | null;
app: {
client_id: string;
name: string;
url: string;
};
note: string | null;
note_url: string | null;
updated_at: string;
created_at: string;
fingerprint: string | null;
user?: {
login: string;
id: number;
node_id: string;
avatar_url: string;
gravatar_id: string | null;
url: string;
html_url: string;
followers_url: string;
following_url: string;
gists_url: string;
starred_url: string;
subscriptions_url: string;
organizations_url: string;
repos_url: string;
events_url: string;
received_events_url: string;
type: string;
site_admin: boolean;
starred_at?: string | undefined;
} | null | undefined;
installation?: {
permissions: {
actions?: "read" | "write" | undefined;
administration?: "read" | "write" | undefined;
checks?: "read" | "write" | undefined;
content_references?: "read" | "write" | undefined;
contents?: "read" | "write" | undefined;
deployments?: "read" | "write" | undefined;
environments?: "read" | "write" | undefined;
issues?: "read" | "write" | undefined;
metadata?: "read" | "write" | undefined;
packages?: "read" | "write" | undefined;
pages?: "read" | "write" | undefined;
pull_requests?: "read" | "write" | undefined;
repository_hooks?: "read" | "write" | undefined;
repository_projects?: "read" | "write" | "admin" | undefined;
secret_scanning_alerts?: "read" | "write" | undefined;
secrets?: "read" | "write" | undefined;
security_events?: "read" | "write" | undefined;
single_file?: "read" | "write" | undefined;
statuses?: "read" | "write" | undefined;
vulnerability_alerts?: "read" | undefined;
workflows?: "write" | undefined;
members?: "read" | "write" | undefined;
organization_administration?: "read" | "write" | undefined;
organization_hooks?: "read" | "write" | undefined;
organization_plan?: "read" | undefined;
organization_projects?: "read" | "write" | "admin" | undefined;
organization_secrets?: "read" | "write" | undefined;
organization_self_hosted_runners?: "read" | "write" | undefined;
organization_user_blocking?: "read" | "write" | undefined;
team_discussions?: "read" | "write" | undefined;
};
repository_selection: "all" | "selected";
single_file_name: string | null;
has_multiple_single_files?: boolean | undefined;
single_file_paths?: string[] | undefined;
repositories_url: string;
account: {
login: string;
id: number;
node_id: string;
avatar_url: string;
gravatar_id: string | null;
url: string;
html_url: string;
followers_url: string;
following_url: string;
gists_url: string;
starred_url: string;
subscriptions_url: string;
organizations_url: string;
repos_url: string;
events_url: string;
received_events_url: string;
type: string;
site_admin: boolean;
starred_at?: string | undefined;
} | null;
} | null | undefined;
}>;
export declare function checkTokenWithState(state: State, options: StateOptions): Promise<{
id: number;
url: string;
scopes: string[] | null;
token: string;
token_last_eight: string | null;
hashed_token: string | null;
app: {
client_id: string;
name: string;
url: string;
};
note: string | null;
note_url: string | null;
updated_at: string;
created_at: string;
fingerprint: string | null;
user?: {
login: string;
id: number;
node_id: string;
avatar_url: string;
gravatar_id: string | null;
url: string;
html_url: string;
followers_url: string;
following_url: string;
gists_url: string;
starred_url: string;
subscriptions_url: string;
organizations_url: string;
repos_url: string;
events_url: string;
received_events_url: string;
type: string;
site_admin: boolean;
starred_at?: string | undefined;
} | null | undefined;
installation?: {
permissions: {
actions?: "read" | "write" | undefined;
administration?: "read" | "write" | undefined;
checks?: "read" | "write" | undefined;
content_references?: "read" | "write" | undefined;
contents?: "read" | "write" | undefined;
deployments?: "read" | "write" | undefined;
environments?: "read" | "write" | undefined;
issues?: "read" | "write" | undefined;
metadata?: "read" | "write" | undefined;
packages?: "read" | "write" | undefined;
pages?: "read" | "write" | undefined;
pull_requests?: "read" | "write" | undefined;
repository_hooks?: "read" | "write" | undefined;
repository_projects?: "read" | "write" | "admin" | undefined;
secret_scanning_alerts?: "read" | "write" | undefined;
secrets?: "read" | "write" | undefined;
security_events?: "read" | "write" | undefined;
single_file?: "read" | "write" | undefined;
statuses?: "read" | "write" | undefined;
vulnerability_alerts?: "read" | undefined;
workflows?: "write" | undefined;
members?: "read" | "write" | undefined;
organization_administration?: "read" | "write" | undefined;
organization_hooks?: "read" | "write" | undefined;
organization_plan?: "read" | undefined;
organization_projects?: "read" | "write" | "admin" | undefined;
organization_secrets?: "read" | "write" | undefined;
organization_self_hosted_runners?: "read" | "write" | undefined;
organization_user_blocking?: "read" | "write" | undefined;
team_discussions?: "read" | "write" | undefined;
};
repository_selection: "all" | "selected";
single_file_name: string | null;
has_multiple_single_files?: boolean | undefined;
single_file_paths?: string[] | undefined;
repositories_url: string;
account: {
login: string;
id: number;
node_id: string;
avatar_url: string;
gravatar_id: string | null;
url: string;
html_url: string;
followers_url: string;
following_url: string;
gists_url: string;
starred_url: string;
subscriptions_url: string;
organizations_url: string;
repos_url: string;
events_url: string;
received_events_url: string;
type: string;
site_admin: boolean;
starred_at?: string | undefined;
} | null;
} | null | undefined;
}>;
export declare type AppCheckToken = (options: StateOptions) => ReturnType<typeof checkTokenWithState>;
export {};
export declare function checkTokenWithState(state: State, options: CheckTokenOptions): Promise<any>;
export interface CheckTokenInterface<TClientType extends ClientType> {
(options: CheckTokenOptions): TClientType extends "oauth-app" ? Promise<OAuthMethods.CheckTokenOAuthAppResponse> : Promise<OAuthMethods.CheckTokenGitHubAppResponse>;
}

@@ -1,21 +0,24 @@

import { State } from "../types";
declare type Options = {
clientId: string;
clientSecret: string;
state: string;
code: string;
};
declare type StateOptions = {
state: string;
code: string;
};
export declare function createToken(options: Options): Promise<{
token: any;
scopes: any;
import * as OAuthAppAuth from "@octokit/auth-oauth-app";
import { ClientType, State } from "../types";
export declare type CreateTokenWebFlowOptions = Omit<OAuthAppAuth.WebFlowAuthOptions, "type">;
export declare type CreateTokenOAuthAppDeviceFlowOptions = Omit<OAuthAppAuth.OAuthAppDeviceFlowAuthOptions, "type">;
export declare type CreateTokenGitHubAppDeviceFlowOptions = Omit<OAuthAppAuth.GitHubAppDeviceFlowAuthOptions, "type">;
export declare function createTokenWithState(state: State, options: CreateTokenWebFlowOptions | CreateTokenOAuthAppDeviceFlowOptions | CreateTokenGitHubAppDeviceFlowOptions): Promise<{
authentication: OAuthAppAuth.OAuthAppUserAuthentication | OAuthAppAuth.GitHubAppUserAuthentication | OAuthAppAuth.GitHubAppUserAuthenticationWithExpiration;
}>;
export declare function createTokenWithState(state: State, options: StateOptions): Promise<{
token: any;
scopes: any;
}>;
export declare type AppCreateToken = (options: StateOptions) => ReturnType<typeof createTokenWithState>;
export {};
export interface CreateTokenInterface<TClientType extends ClientType> {
(options: CreateTokenWebFlowOptions): TClientType extends "oauth-app" ? Promise<{
authentication: OAuthAppAuth.OAuthAppUserAuthentication;
}> : Promise<{
authentication: OAuthAppAuth.GitHubAppUserAuthentication;
} | {
authentication: OAuthAppAuth.GitHubAppUserAuthenticationWithExpiration;
}>;
(options: TClientType extends "oauth-app" ? CreateTokenOAuthAppDeviceFlowOptions : CreateTokenGitHubAppDeviceFlowOptions): TClientType extends "oauth-app" ? Promise<{
authentication: OAuthAppAuth.OAuthAppUserAuthentication;
}> : Promise<{
authentication: OAuthAppAuth.GitHubAppUserAuthentication;
} | {
authentication: OAuthAppAuth.GitHubAppUserAuthenticationWithExpiration;
}>;
}

@@ -0,13 +1,9 @@

import * as OAuthMethods from "@octokit/oauth-methods";
import { State } from "../types";
declare type Options = {
clientId: string;
clientSecret: string;
export declare type DeleteAuthorizationOptions = {
token: string;
};
declare type StateOptions = {
token: string;
};
export declare function deleteAuthorization(options: Options): Promise<never>;
export declare function deleteAuthorizationWithState(state: State, options: StateOptions): Promise<never>;
export declare type AppDeleteAuthorization = (options: StateOptions) => ReturnType<typeof deleteAuthorizationWithState>;
export {};
export declare function deleteAuthorizationWithState(state: State, options: DeleteAuthorizationOptions): Promise<OAuthMethods.DeleteAuthorizationResponse>;
export interface DeleteAuthorizationInterface {
(options: DeleteAuthorizationOptions): Promise<OAuthMethods.DeleteAuthorizationResponse>;
}

@@ -0,13 +1,9 @@

import * as OAuthMethods from "@octokit/oauth-methods";
import { State } from "../types";
declare type Options = {
clientId: string;
clientSecret: string;
export declare type DeleteTokenOptions = {
token: string;
};
declare type StateOptions = {
token: string;
};
export declare function deleteToken(options: Options): Promise<never>;
export declare function deleteTokenWithState(state: State, options: StateOptions): Promise<never>;
export declare type AppDeleteToken = (options: StateOptions) => ReturnType<typeof deleteTokenWithState>;
export {};
export declare function deleteTokenWithState(state: State, options: DeleteTokenOptions): Promise<OAuthMethods.DeleteTokenResponse>;
export interface DeleteTokenInterface {
(options: DeleteTokenOptions): Promise<OAuthMethods.DeleteTokenResponse>;
}

@@ -1,209 +0,9 @@

import { State } from "../types";
declare type Options = {
clientId: string;
clientSecret: string;
import * as OAuthMethods from "@octokit/oauth-methods";
import { ClientType, State } from "../types";
export declare type ResetTokenOptions = {
token: string;
};
declare type StateOptions = {
token: string;
};
export declare function resetToken(options: Options): Promise<{
id: number;
url: string;
scopes: string[] | null;
token: string;
token_last_eight: string | null;
hashed_token: string | null;
app: {
client_id: string;
name: string;
url: string;
};
note: string | null;
note_url: string | null;
updated_at: string;
created_at: string;
fingerprint: string | null;
user?: {
login: string;
id: number;
node_id: string;
avatar_url: string;
gravatar_id: string | null;
url: string;
html_url: string;
followers_url: string;
following_url: string;
gists_url: string;
starred_url: string;
subscriptions_url: string;
organizations_url: string;
repos_url: string;
events_url: string;
received_events_url: string;
type: string;
site_admin: boolean;
starred_at?: string | undefined;
} | null | undefined;
installation?: {
permissions: {
actions?: "read" | "write" | undefined;
administration?: "read" | "write" | undefined;
checks?: "read" | "write" | undefined;
content_references?: "read" | "write" | undefined;
contents?: "read" | "write" | undefined;
deployments?: "read" | "write" | undefined;
environments?: "read" | "write" | undefined;
issues?: "read" | "write" | undefined;
metadata?: "read" | "write" | undefined;
packages?: "read" | "write" | undefined;
pages?: "read" | "write" | undefined;
pull_requests?: "read" | "write" | undefined;
repository_hooks?: "read" | "write" | undefined;
repository_projects?: "read" | "write" | "admin" | undefined;
secret_scanning_alerts?: "read" | "write" | undefined;
secrets?: "read" | "write" | undefined;
security_events?: "read" | "write" | undefined;
single_file?: "read" | "write" | undefined;
statuses?: "read" | "write" | undefined;
vulnerability_alerts?: "read" | undefined;
workflows?: "write" | undefined;
members?: "read" | "write" | undefined;
organization_administration?: "read" | "write" | undefined;
organization_hooks?: "read" | "write" | undefined;
organization_plan?: "read" | undefined;
organization_projects?: "read" | "write" | "admin" | undefined;
organization_secrets?: "read" | "write" | undefined;
organization_self_hosted_runners?: "read" | "write" | undefined;
organization_user_blocking?: "read" | "write" | undefined;
team_discussions?: "read" | "write" | undefined;
};
repository_selection: "all" | "selected";
single_file_name: string | null;
has_multiple_single_files?: boolean | undefined;
single_file_paths?: string[] | undefined;
repositories_url: string;
account: {
login: string;
id: number;
node_id: string;
avatar_url: string;
gravatar_id: string | null;
url: string;
html_url: string;
followers_url: string;
following_url: string;
gists_url: string;
starred_url: string;
subscriptions_url: string;
organizations_url: string;
repos_url: string;
events_url: string;
received_events_url: string;
type: string;
site_admin: boolean;
starred_at?: string | undefined;
} | null;
} | null | undefined;
}>;
export declare function resetTokenWithState(state: State, options: StateOptions): Promise<{
id: number;
url: string;
scopes: string[] | null;
token: string;
token_last_eight: string | null;
hashed_token: string | null;
app: {
client_id: string;
name: string;
url: string;
};
note: string | null;
note_url: string | null;
updated_at: string;
created_at: string;
fingerprint: string | null;
user?: {
login: string;
id: number;
node_id: string;
avatar_url: string;
gravatar_id: string | null;
url: string;
html_url: string;
followers_url: string;
following_url: string;
gists_url: string;
starred_url: string;
subscriptions_url: string;
organizations_url: string;
repos_url: string;
events_url: string;
received_events_url: string;
type: string;
site_admin: boolean;
starred_at?: string | undefined;
} | null | undefined;
installation?: {
permissions: {
actions?: "read" | "write" | undefined;
administration?: "read" | "write" | undefined;
checks?: "read" | "write" | undefined;
content_references?: "read" | "write" | undefined;
contents?: "read" | "write" | undefined;
deployments?: "read" | "write" | undefined;
environments?: "read" | "write" | undefined;
issues?: "read" | "write" | undefined;
metadata?: "read" | "write" | undefined;
packages?: "read" | "write" | undefined;
pages?: "read" | "write" | undefined;
pull_requests?: "read" | "write" | undefined;
repository_hooks?: "read" | "write" | undefined;
repository_projects?: "read" | "write" | "admin" | undefined;
secret_scanning_alerts?: "read" | "write" | undefined;
secrets?: "read" | "write" | undefined;
security_events?: "read" | "write" | undefined;
single_file?: "read" | "write" | undefined;
statuses?: "read" | "write" | undefined;
vulnerability_alerts?: "read" | undefined;
workflows?: "write" | undefined;
members?: "read" | "write" | undefined;
organization_administration?: "read" | "write" | undefined;
organization_hooks?: "read" | "write" | undefined;
organization_plan?: "read" | undefined;
organization_projects?: "read" | "write" | "admin" | undefined;
organization_secrets?: "read" | "write" | undefined;
organization_self_hosted_runners?: "read" | "write" | undefined;
organization_user_blocking?: "read" | "write" | undefined;
team_discussions?: "read" | "write" | undefined;
};
repository_selection: "all" | "selected";
single_file_name: string | null;
has_multiple_single_files?: boolean | undefined;
single_file_paths?: string[] | undefined;
repositories_url: string;
account: {
login: string;
id: number;
node_id: string;
avatar_url: string;
gravatar_id: string | null;
url: string;
html_url: string;
followers_url: string;
following_url: string;
gists_url: string;
starred_url: string;
subscriptions_url: string;
organizations_url: string;
repos_url: string;
events_url: string;
received_events_url: string;
type: string;
site_admin: boolean;
starred_at?: string | undefined;
} | null;
} | null | undefined;
}>;
export declare type AppResetToken = (options: StateOptions) => ReturnType<typeof resetTokenWithState>;
export {};
export declare function resetTokenWithState(state: State, options: ResetTokenOptions): Promise<OAuthMethods.ResetTokenOAuthAppResponse | OAuthMethods.ResetTokenGitHubAppResponse>;
export interface ResetTokenInterface<TClientType extends ClientType> {
(options: ResetTokenOptions): TClientType extends "oauth-app" ? Promise<OAuthMethods.ResetTokenOAuthAppResponse> : Promise<OAuthMethods.ResetTokenGitHubAppResponse>;
}

@@ -21,2 +21,3 @@ /// <reference types="node" />

redirectUrl?: string;
refreshToken?: string;
};

@@ -23,0 +24,0 @@ };

@@ -0,2 +1,4 @@

import { OAuthAppUserAuthentication, GitHubAppUserAuthentication, GitHubAppUserAuthenticationWithExpiration } from "@octokit/auth-oauth-app";
import { OAuthAppOctokit } from "./oauth-app-octokit";
export declare type ClientType = "oauth-app" | "github-app";
export declare type Scope = string;

@@ -7,8 +9,7 @@ export declare type ClientId = string;

export declare type EventName = "token" | "authorization";
export declare type ActionName = "created" | "reset" | "deleted" | "before_deleted";
export declare type EventAndActionName = "token" | "token.created" | "token.reset" | "token.deleted" | "token.before_deleted" | "authorization" | "authorization.before_deleted" | "authorization.deleted";
export declare type ConstructorOptions = {
export declare type ActionName = "created" | "reset" | "deleted" | "refreshed" | "scoped";
export declare type EventAndActionName = "token" | "token.created" | "token.reset" | "token.refreshed" | "token.scoped" | "token.deleted" | "authorization" | "authorization.deleted";
declare type CommonConstructorOptions = {
clientId: ClientId;
clientSecret: ClientSecret;
defaultScopes?: Scope[];
allowSignup?: boolean;

@@ -19,4 +20,11 @@ baseUrl?: string;

};
export declare type ConstructorOptions<TClientType extends ClientType> = TClientType extends "oauth-app" ? CommonConstructorOptions & {
clientType?: TClientType;
defaultScopes?: Scope[];
} : CommonConstructorOptions & {
clientType?: TClientType;
};
export declare type OctokitInstance = InstanceType<typeof OAuthAppOctokit>;
export declare type State = {
clientType: ClientType;
clientId: ClientId;

@@ -31,6 +39,6 @@ clientSecret: ClientSecret;

eventHandlers: {
[key: string]: EventHandler[];
[key: string]: EventHandler<ClientType>[];
};
};
export declare type EventHandlerContext = {
export declare type EventHandlerContext<TClientType extends ClientType> = TClientType extends "oauth-app" ? {
name: EventName;

@@ -41,7 +49,12 @@ action: ActionName;

octokit: InstanceType<typeof OAuthAppOctokit>;
authentication?: OAuthAppUserAuthentication;
} : {
name: EventName;
action: ActionName;
token: Token;
octokit: InstanceType<typeof OAuthAppOctokit>;
authentication?: GitHubAppUserAuthentication | GitHubAppUserAuthenticationWithExpiration;
};
export declare type EventHandler = (context: EventHandlerContext) => void;
export declare type AddEventHandler = (eventName: EventAndActionName | EventAndActionName[], eventHandler: EventHandler) => void;
declare type Diff<T, U> = T extends U ? never : T;
export declare type RequiredExceptFor<T, TOptional extends keyof T> = Pick<T, Diff<keyof T, TOptional>> & Partial<T>;
export declare type EventHandler<TClientType extends ClientType> = (context: EventHandlerContext<TClientType>) => void;
export declare type AddEventHandler<TClientType extends ClientType> = (eventName: EventAndActionName | EventAndActionName[], eventHandler: EventHandler<TClientType>) => void;
export {};

@@ -1,1 +0,1 @@

export declare const VERSION = "2.1.0";
export declare const VERSION = "3.0.0";
{
"name": "@octokit/oauth-app",
"description": "GitHub OAuth toolset for Node.js",
"version": "2.1.0",
"version": "3.0.0",
"license": "MIT",

@@ -20,6 +20,8 @@ "files": [

"dependencies": {
"@octokit/auth-oauth-app": "^3.0.0",
"@octokit/auth-oauth-app": "^4.0.0",
"@octokit/auth-oauth-user": "^1.2.3",
"@octokit/auth-unauthenticated": "^2.0.0",
"@octokit/core": "^3.0.0",
"@octokit/oauth-authorization-url": "^4.2.1",
"@octokit/oauth-methods": "^1.2.2",
"@types/btoa-lite": "^1.0.0",

@@ -26,0 +28,0 @@ "btoa-lite": "^1.0.0",

@@ -14,2 +14,4 @@ # oauth-app.js

- [Usage](#usage)
- [For OAuth Apps](#for-oauth-apps)
- [For GitHub Apps](#for-github-apps)
- [Examples](#examples)

@@ -19,17 +21,15 @@ - [Constructor options](#constructor-options)

- [`app.octokit`](#appoctokit)
- [`app.getAuthorizationUrl(options)`](#appgetauthorizationurloptions)
- [`app.getUserOctokit(options)`](#appgetuseroctokitoptions)
- [`app.getWebFlowAuthorizationUrl(options)`](#appgetwebflowauthorizationurloptions)
- [`app.createToken(options)`](#appcreatetokenoptions)
- [For OAuth Web flow](#for-oauth-web-flow)
- [For OAuth Device flow](#for-oauth-device-flow)
- [`app.checkToken(options)`](#appchecktokenoptions)
- [`app.resetToken(options)`](#appresettokenoptions)
- [`app.refreshToken(options)`](#apprefreshtokenoptions)
- [`app.scopeToken(options)`](#appscopetokenoptions)
- [`app.deleteToken(options)`](#appdeletetokenoptions)
- [`app.deleteAuthorization(options)`](#appdeleteauthorizationoptions)
- [Stateless methods](#stateless-methods)
- [`getAuthorizationUrl(options)`](#getauthorizationurloptions)
- [`createToken(options)`](#createtokenoptions)
- [`checkToken(options)`](#checktokenoptions)
- [`resetToken(options)`](#resettokenoptions)
- [`deleteToken(options)`](#deletetokenoptions)
- [`deleteAuthorization(options)`](#deleteauthorizationoptions)
- [Middlewares](#middlewares)
- [`getNodeMiddleware(app, options)`](#getnodemiddlewareapp-options)
- [`createNodeMiddleware(app, options)`](#createnodemiddlewareapp-options)
- [Contributing](#contributing)

@@ -63,8 +63,15 @@ - [License](#license)

</td></tr>
</tbody>
</table>
### For OAuth Apps
```js
const { OAuthApp, getNodeMiddleware } = require("@octokit/oauth-app");
const { OAuthApp, createNodeMiddleware } = require("@octokit/oauth-app");
const app = new OAuthApp({
clientId: "0123",
clientSecret: "0123secret",
clientType: "oauth-app",
clientId: "1234567890abcdef1234",
clientSecret: "1234567890abcdef1234567890abcdef12345678",
});

@@ -77,3 +84,3 @@

require("http").createServer(getNodeMiddleware(app)).listen(3000);
require("http").createServer(createNodeMiddleware(app)).listen(3000);
// can now receive user authorization callbacks at /api/github/oauth/callback

@@ -83,6 +90,25 @@ // See all endpoints at https://github.com/octokit/oauth-app.js#middlewares

</td></tr>
</tbody>
</table>
### For GitHub Apps
GitHub Apps do not support `scopes`. If the GitHub App has expiring user tokens enabled, the token used for the `octokit` instance will be refreshed automatically, and the additional refresh-releated properties will be passed to the `"token"` event handler.
```js
const { OAuthApp, createNodeMiddleware } = require("@octokit/oauth-app");
const app = new OAuthApp({
clientType: "github-app",
clientId: "lv1.1234567890abcdef",
clientSecret: "1234567890abcdef1234567890abcdef12345678",
});
app.on("token", async ({ token, octokit, expiresAt }) => {
const { data } = await octokit.request("GET /user");
console.log(`Token retrieved for ${data.login}`);
});
require("http").createServer(createNodeMiddleware(app)).listen(3000);
// can now receive user authorization callbacks at /api/github/oauth/callback
// See all endpoints at https://github.com/octokit/oauth-app.js#middlewares
```
## Examples

@@ -135,2 +161,13 @@

<th>
<code>clientType</code>
</th>
<th>
<code>string</code>
</th>
<td>
Either <code>"oauth-app"</code> or <code>"github-app"</code>. Defaults to <code>"oauth-app"</code>.
</td>
</tr>
<tr>
<th>
<code>allowSignup</code>

@@ -142,3 +179,3 @@ </th>

<td>
Sets the default value for <code>app.getAuthorizationUrl(options)</code>.
Sets the default value for <code>app.getWebFlowAuthorizationUrl(options)</code>.
</td>

@@ -155,4 +192,6 @@ </tr>

Sets the default <code>scopes</code> value for <code>app.getAuthorizationUrl(options)</code>. See [available scopes](https://docs.github.com/en/developers/apps/scopes-for-oauth-apps#available-scopes)
Only relevant when `clientType` is set to `"oauth-app"`.
Sets the default `scopes` value for `app.getWebFlowAuthorizationUrl(options)`. See [available scopes](https://docs.github.com/en/developers/apps/scopes-for-oauth-apps#available-scopes)
</td></tr>

@@ -179,3 +218,3 @@ <tr>

You can pass in your own Octokit constructor with custom defaults and plugins. The Octokit Constructor must accept `options.auth` to be set to an OAuth access token string, such as [`@octokit/auth-token`](https://github.com/octokit/auth-token.js) does.
You can pass in your own Octokit constructor with custom defaults and plugins. The Octokit Constructor must use an authenticatio strategy that is compatible with[`@octokit/auth-oauth-app](https://github.com/octokit/auth-oauth-app.js/#readme).

@@ -185,6 +224,6 @@ For usage with enterprise, set `baseUrl` to the hostname + `/api/v3`. Example:

```js
const { Octokit } = require("@octokit/core");
const { Octokit } = require("@octokit/oauth-app");
new OAuthApp({
clientId: 123,
clientSecret: "secret",
clientId: "1234567890abcdef1234",
clientSecret: "1234567890abcdef1234567890abcdef12345678",
Octokit: Octokit.defaults({

@@ -196,3 +235,3 @@ baseUrl: "https://ghe.my-company.com/api/v3",

Defaults to [`@octokit/core`](https://github.com/octokit/core.js).
Defaults to `@octokit/oauth-app`'s owne `Octokit` constructor which can be imported separately from `OAuthApp`. It's [`@octokit/core`](https://github.com/octokit/core.js) with the [`@octokit/auth-oauth-user`](https://github.com/octokit/auth-oauth-user.js/#readme) authentication strategy.

@@ -218,5 +257,5 @@ </td></tr>

- `token.reset`
- `token.refreshed` (GitHub Apps only)
- `token.scoped` (GitHub Apps only)
- `token.deleted`
- `token.before_deleted`
- `authorization.before_deleted`
- `authorization.deleted`

@@ -262,3 +301,3 @@

<td>
Action of the event. One of: <code>created</code>, <code>reset</code>, <code>deleted</code>, <code>before_deleted</code>
Action of the event. One of: <code>created</code>, <code>reset</code>, <code>deleted</code>
</td>

@@ -268,10 +307,12 @@ </tr>

<th>
<code>context.token</code>
<code>context.authentication</code>
</th>
<th>
<code>string</code>
<code>object</code>
</th>
<td>
The OAuth access token.
</td>
The OAuth authentication object. See https://github.com/octokit/auth-oauth-user.js/#authentication-object
</td>
</tr>

@@ -287,21 +328,8 @@ <tr>

Authenticated instance using the `Octokit` option passed to the constructor.
Authenticated instance using the `Octokit` option passed to the constructor and [`@octokit/auth-oauth-user`](https://github.com/octokit/auth-oauth-user.js/#readme) as authentication strategy.
For `"token.deleted"` and `"authorization.deleted"` events the `octokit` instance is unauthenticated.
The `octokit` instance is unauthenticated for `"token.deleted"` and `"authorization.deleted"` events.
</td></tr>
<tr>
<th>
<code>context.scopes</code>
</th>
<th>
<code>Array of strings</code>
</th>
<td>
An array of scopes the `context.token` has access to.
Not set for `"token.before_deleted"`, `"token.deleted"`, `"authorization.before_deleted"`, and `"authorization.deleted"` events.
</td></tr>
</td>
</tr>
</tbody>

@@ -314,8 +342,18 @@ </table>

## `app.getAuthorizationUrl(options)`
## `app.getUserOctokit(options)`
Returns a URL string.
```js
const { octokit } = await app.getUserOctokit({ code: "code123" });
```
`options` are the same as in [`app.createToken(options)`](#appcreatetokenoptions)
The `octokit` instance is authorized using the user access token if the app is an OAuth app and a user-to-server token if the app is a GitHub app. If the token expires it will be refreshed automatically.
## `app.getWebFlowAuthorizationUrl(options)`
Returns and object with all options and a `url` property which is the authorization URL. See https://github.com/octokit/oauth-methods.js/#getwebflowauthorizationurl
```js
const url = app.getAuthorizationUrl({
const { url } = app.getWebFlowAuthorizationUrl({
state: "state123",

@@ -402,4 +440,10 @@ scopes: ["repo"],

The method can be used for both, the [OAuth Web Flow](https://docs.github.com/en/developers/apps/authorizing-oauth-apps#web-application-flow) and the [OAuth Device Flow](https://docs.github.com/en/developers/apps/authorizing-oauth-apps#device-flow).
### For OAuth Web flow
For the web flow, you have to pass the `code` from URL redirect described in [step 2](https://docs.github.com/en/developers/apps/authorizing-oauth-apps#2-users-are-redirected-back-to-your-site-by-github).
```js
const { token, scopes } = await app.createToken({
const { token } = await app.createToken({
state: "state123",

@@ -450,5 +494,9 @@ code: "code123",

Resolves with `result`
Resolves with with an [user authentication object](https://github.com/octokit/auth-oauth-app.js#authentication-object)
<table>
### For OAuth Device flow
For the device flow, you have to pass a `onVerification` callback function, which prompts the user to enter the received user code at the received authorization URL.
<table width="100%">
<thead align=left>

@@ -470,14 +518,31 @@ <tr>

<th>
<code>result.token</code>
<code>onVerification</code>
</th>
<th>
<code>string</code>
<code>function</code>
</th>
<td>
The OAuth access token
</td>
**Required**. A function that is called once the device and user codes were retrieved
The `onVerification()` callback can be used to pause until the user completes step 2, which might result in a better user experience.
```js
const auth = createOAuthUserAuth({
clientId: "1234567890abcdef1234",
clientSecret: "1234567890abcdef1234567890abcdef12345678",
onVerification(verification) {
console.log("Open %s", verification.verification_uri);
console.log("Enter code: %s", verification.user_code);
await prompt("press enter when you are ready to continue")
},
});
```
</td>
</tr>
<tr>
<th>
<code>result.scopes</code>
<code>scopes</code>
</th>

@@ -488,4 +553,8 @@ <th>

<td>
The names of the scopes the token has access to
</td>
Only relevant if `app.type` is `"oauth-app"`. Scopes are not supported by GitHub apps.
Array of OAuth scope names that the user access token should be granted. Defaults to no scopes (`[]`).
</td>
</tr>

@@ -495,2 +564,4 @@ </tbody>

Resolves with with an [user authentication object](https://github.com/octokit/auth-oauth-app.js#authentication-object)
## `app.checkToken(options)`

@@ -541,3 +612,3 @@

Resolves with response body from ["Check a token" request](https://docs.github.com/en/rest/reference/apps#check-a-token).
Resolves with response body from ["Check a token" request](https://docs.github.com/en/rest/reference/apps#check-a-token) with an additional `authentication` property which is a [user authentication object](https://github.com/octokit/auth-oauth-app.js#authentication-object).

@@ -547,3 +618,3 @@ ## `app.resetToken(options)`

```js
const { token } = await app.resetToken({
const { data, authentication } = await app.resetToken({
token: "token123",

@@ -583,51 +654,12 @@ });

Resolves with response body from ["Reset a token" request](https://docs.github.com/en/rest/reference/apps#reset-a-token).
Resolves with response body from ["Reset a token" request](https://docs.github.com/en/rest/reference/apps#reset-a-token) with an additional `authentication` property which is a [user authentication object](https://github.com/octokit/auth-oauth-app.js#authentication-object).
## `app.deleteToken(options)`
## `app.refreshToken(options)`
```js
await app.deleteToken({
token: "token123",
});
// "token123" is no longer valid.
```
Expiring tokens are only supported by GitHub Apps, and only if expiring user tokens are enabled.
<table width="100%">
<thead align=left>
<tr>
<th width=150>
name
</th>
<th width=70>
type
</th>
<th>
description
</th>
</tr>
</thead>
<tbody align=left valign=top>
<tr>
<th>
<code>token</code>
</th>
<th>
<code>string</code>
</th>
<td>
<strong>Required</strong>.
</td>
</tr>
</tbody>
</table>
Resolves with response body from ["Delete a token" request](https://docs.github.com/en/rest/reference/apps#delete-an-app-token).
## `app.deleteAuthorization(options)`
```js
await app.deleteAuthorization({
token: "token123",
const { data, authentication } = await app.refreshToken({
refreshToken: "refreshtoken123",
});
// "token123" is no longer valid, and no tokens can be created until the app gets re-authorized.
```

@@ -652,3 +684,3 @@

<th>
<code>token</code>
<code>refreshToken</code>
</th>

@@ -665,150 +697,24 @@ <th>

Resolves with response body from ["Delete an app authorization" request](https://docs.github.com/en/rest/reference/apps#delete-an-app-authorization).
Resolves with response body from ["Renewing a user token with a refresh token" request](https://docs.github.com/en/developers/apps/refreshing-user-to-server-access-tokens#renewing-a-user-token-with-a-refresh-token) (JSON) with an additional `authentication` property which is a [user authentication object](https://github.com/octokit/auth-oauth-app.js#authentication-object).
## Stateless methods
## `app.scopeToken(options)`
Each method can be loaded separately to minimize the payload. That is particularly useful for serverless environment, as the payload will be the smallest possible.
Scoping a token is only supported by GitHub Apps. "Scoping" in this context means to limit access to a selected installation, with a subset of repositories and permissions.
```js
const {
getAuthorizationUrl,
createToken,
checkToken,
resetToken,
deleteToken,
deleteAuthorization,
} = require("@octokit/oauth-app");
```
### `getAuthorizationUrl(options)`
Returns a URL string.
```js
const { getAuthorizationUrl } = require("@octokit/oauth-app");
const url = getAuthorizationUrl({
clientId: "0123",
state: "state123",
const { data, authentication } = await app.scopeToken({
clientType: "github-app",
clientId: "lv1.1234567890abcdef",
clientSecret: "1234567890abcdef12347890abcdef12345678",
token: "usertoken123",
target: "octokit",
repositories: ["oauth-app.js"],
permissions: {
issues: "write",
},
});
```
<table>
<thead align=left>
<tr>
<th width=150>
name
</th>
<th width=70>
type
</th>
<th>
description
</th>
</tr>
</thead>
<tbody align=left valign=top>
<tr>
<th>
<code>clientId</code>
</th>
<th>
<code>string</code>
</th>
<td>
<strong>Required</strong>. The client ID you received from GitHub when you registered.
</td>
</tr>
<tr>
<th>
<code>state</code>
</th>
<th>
<code>string</code>
</th>
<td>
<strong>Required</strong>. An unguessable random string. It is used to protect against cross-site request forgery attacks.
Defaults to <code>Math.random().toString(36).substr(2)</code>.
</td>
</tr>
<tr>
<th>
<code>redirectUrl</code>
</th>
<th>
<code>string</code>
</th>
<td>
The URL in your application where users will be sent after authorization. See <a href="https://docs.github.com/en/developers/apps/authorizing-oauth-apps#redirect-urls">Redirect URLs</a> in GitHub’s Developer Guide.
</td>
</tr>
<tr>
<th>
<code>login</code>
</th>
<th>
<code>string</code>
</th>
<td>
Suggests a specific account to use for signing in and authorizing the app.
</td>
</tr>
<tr>
<th>
<code>scopes</code>
</th>
<th>
<code>array of strings</code>
</th>
<td>
An array of scope names (or: space-delimited list of scopes). If not provided, scope defaults to an empty list for users that have not authorized any scopes for the application. For users who have authorized scopes for the application, the user won't be shown the OAuth authorization page with the list of scopes. Instead, this step of the flow will automatically complete with the set of scopes the user has authorized for the application. For example, if a user has already performed the web flow twice and has authorized one token with user scope and another token with repo scope, a third web flow that does not provide a scope will receive a token with user and repo scope.
</td>
</tr>
<tr>
<th>
<code>allowSignup</code>
</th>
<th>
<code>boolean</code>
</th>
<td>
Whether or not unauthenticated users will be offered an option to sign up for GitHub during the OAuth flow. The default is <code>true</code>. Use <code>false</code> in the case that a policy prohibits signups.
</td>
</tr>
<tr>
<th>
<code>log</code>
</th>
<th>
<code>object</code>
</th>
<td>
When invalid options are passed, warnings are logged using <code>log.warn(message)</code>. Defaults to <a href="https://developer.mozilla.org/en-US/docs/Web/API/console"><code>console</code></a>.
</td>
</tr>
<tr>
<th>
<code>baseUrl</code>
</th>
<th>
<code>string</code>
</th>
<td>
When using GitHub Enterprise Server, set the baseUrl to the origin, e.g. <code>https://github.my-enterprise.com/</code>.
</td>
</tr>
</tbody>
</table>
Options
### `createToken(options)`
```js
const { createToken } = require("@octokit/oauth-app");
const { token, scopes } = await createToken({
clientId: "0123",
clientSecret: "0123secret",
state: "state123",
code: "code123",
});
```
<table width="100%">

@@ -831,31 +737,9 @@ <thead align=left>

<th>
<code>clientId</code>
<code>target</code>
</th>
<th>
<code>number</code>
</th>
<td>
<strong>Required</strong>. Find <strong>Client ID</strong> on the app’s about page in settings.
</td>
</tr>
<tr>
<th>
<code>clientSecret</code>
</th>
<th>
<code>number</code>
</th>
<td>
<strong>Required</strong>. Find <strong>Client Secret</strong> on the app’s about page in settings.
</td>
</tr>
<tr>
<th>
<code>code</code>
</th>
<th>
<code>string</code>
</th>
<td>
<strong>Required</strong>. Pass the code that was passed in the <code>?code</code> query parameter in the authorization redirect URL.
<strong>Required unless <code>targetId</code> is set</strong>. The name of the user or organization to scope the user-to-server access token to.
</td>

@@ -865,101 +749,31 @@ </tr>

<th>
<code>state</code>
<code>targetId</code>
</th>
<th>
<code>string</code>
<code>integer</code>
</th>
<td>
<strong>Required</strong>. Pass the state that was passed in the <code>?state</code> query parameter in the authorization redirect URL.
<strong>Required unless <code>target</code> is set</strong>. The ID of the user or organization to scope the user-to-server access token to.
</td>
</tr>
</tbody>
</table>
Resolves with `result`
<table>
<thead align=left>
<tr>
<th width=150>
name
</th>
<th width=70>
type
</th>
<th>
description
<code>repositories</code>
</th>
</tr>
</thead>
<tbody align=left valign=top>
<tr>
<th>
<code>result.token</code>
</th>
<th>
<code>string</code>
</th>
<td>
The OAuth access token
</td>
</tr>
<tr>
<th>
<code>result.scopes</code>
</th>
<th>
<code>array of strings</code>
</th>
<td>
The names of the scopes the token has access to
The list of repository names to scope the user-to-server access token to. <code>repositories</code> may not be specified if <code>repository_ids</code> is specified.
</td>
</tr>
</tbody>
</table>
### `checkToken(options)`
```js
const { checkToken } = require("@octokit/oauth-app");
try {
const { created_at, app, user } = await checkToken({
clientId: "0123",
clientSecret: "0123secret",
token: "token123",
});
console.log(
`token valid, created on %s by %s for %s`,
created_at,
user.login,
app.name
);
} catch (error) {
// token invalid or request error
}
```
<table width="100%">
<thead align=left>
<tr>
<th width=150>
name
</th>
<th width=70>
type
</th>
<th>
description
<code>repository_ids</code>
</th>
</tr>
</thead>
<tbody align=left valign=top>
<tr>
<th>
<code>clientId</code>
<code>array of integers</code>
</th>
<th>
<code>number</code>
</th>
<td>
<strong>Required</strong>. Find <strong>Client ID</strong> on the app’s about page in settings.
The list of repository IDs to scope the user-to-server access token to. <code>repositories</code> may not be specified if <code>repositories</code> is specified.
</td>

@@ -969,37 +783,23 @@ </tr>

<th>
<code>clientSecret</code>
<code>permissions</code>
</th>
<th>
<code>number</code>
<code>object</code>
</th>
<td>
<strong>Required</strong>. Find <strong>Client Secret</strong> on the app’s about page in settings.
The permissions granted to the user-to-server access token. See <a href="https://docs.github.com/en/rest/reference/permissions-required-for-github-apps">GitHub App Permissions</a>.
</td>
</tr>
<tr>
<th>
<code>token</code>
</th>
<th>
<code>string</code>
</th>
<td>
<strong>Required</strong>.
</td>
</tr>
</tbody>
</table>
Resolves with response body from ["Check a token" request](https://docs.github.com/en/rest/reference/apps#check-a-token).
Resolves with response body from ["Create a scoped access token" request](https://docs.github.com/en/rest/reference/apps#create-a-scoped-access-token) with an additional `authentication` property which is a [user authentication object](https://github.com/octokit/auth-oauth-app.js#authentication-object).
### `resetToken(options)`
## `app.deleteToken(options)`
```js
const { resetToken } = require("@octokit/oauth-app");
const { token } = await resetToken({
clientId: "0123",
clientSecret: "0123secret",
await app.deleteToken({
token: "token123",
});
// "token123" is no longer valid. Use `token` instead
// "token123" is no longer valid.
```

@@ -1024,24 +824,2 @@

<th>
<code>clientId</code>
</th>
<th>
<code>number</code>
</th>
<td>
<strong>Required</strong>. Find <strong>Client ID</strong> on the app’s about page in settings.
</td>
</tr>
<tr>
<th>
<code>clientSecret</code>
</th>
<th>
<code>number</code>
</th>
<td>
<strong>Required</strong>. Find <strong>Client Secret</strong> on the app’s about page in settings.
</td>
</tr>
<tr>
<th>
<code>token</code>

@@ -1059,79 +837,11 @@ </th>

Resolves with response body from ["Reset a token" request](https://docs.github.com/en/rest/reference/apps#reset-a-token).
### `deleteToken(options)`
```js
const { deleteToken } = require("@octokit/oauth-app");
await deleteToken({
clientId: "0123",
clientSecret: "0123secret",
token: "token123",
});
// "token123" is no longer valid
```
<table width="100%">
<thead align=left>
<tr>
<th width=150>
name
</th>
<th width=70>
type
</th>
<th>
description
</th>
</tr>
</thead>
<tbody align=left valign=top>
<tr>
<th>
<code>clientId</code>
</th>
<th>
<code>number</code>
</th>
<td>
<strong>Required</strong>. Find <strong>Client ID</strong> on the app’s about page in settings.
</td>
</tr>
<tr>
<th>
<code>clientSecret</code>
</th>
<th>
<code>number</code>
</th>
<td>
<strong>Required</strong>. Find <strong>Client Secret</strong> on the app’s about page in settings.
</td>
</tr>
<tr>
<th>
<code>token</code>
</th>
<th>
<code>string</code>
</th>
<td>
<strong>Required</strong>.
</td>
</tr>
</tbody>
</table>
Resolves with response body from ["Delete a token" request](https://docs.github.com/en/rest/reference/apps#delete-an-app-token).
### `deleteAuthorization(options)`
## `app.deleteAuthorization(options)`
```js
const { deleteAuthorization } = require("@octokit/oauth-app");
await deleteAuthorization({
clientId: "0123",
clientSecret: "0123secret",
await app.deleteAuthorization({
token: "token123",
});
// "token123" is no longer valid
// "token123" is no longer valid, and no tokens can be created until the app gets re-authorized.
```

@@ -1156,24 +866,2 @@

<th>
<code>clientId</code>
</th>
<th>
<code>number</code>
</th>
<td>
<strong>Required</strong>. Find <strong>Client ID</strong> on the app’s about page in settings.
</td>
</tr>
<tr>
<th>
<code>clientSecret</code>
</th>
<th>
<code>number</code>
</th>
<td>
<strong>Required</strong>. Find <strong>Client Secret</strong> on the app’s about page in settings.
</td>
</tr>
<tr>
<th>
<code>token</code>

@@ -1199,13 +887,15 @@ </th>

| Route | Route Description |
| -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `GET /api/github/oauth/login` | Redirects to GitHub's authorization endpoint. Accepts optional `?state` and `?scopes` query parameters. `?scopes` is a comma-separated list of [supported OAuth scope names](https://docs.github.com/en/developers/apps/scopes-for-oauth-apps#available-scopes) |
| `GET /api/github/oauth/callback` | The client's redirect endpoint. This is where the `token` event gets triggered |
| `POST /api/github/oauth/token` | Exchange an authorization code for an OAuth Access token. If successful, the `token` event gets triggered. |
| `GET /api/github/oauth/token` | Check if token is valid. Must authenticate using token in `Authorization` header. Uses GitHub's [`POST /applications/{client_id}/token`](https://docs.github.com/en/rest/reference/apps#check-a-token) endpoint |
| `PATCH /api/github/oauth/token` | Resets a token (invalidates current one, returns new token). Must authenticate using token in `Authorization` header. Uses GitHub's [`PATCH /applications/{client_id}/token`](https://docs.github.com/en/rest/reference/apps#reset-a-token) endpoint. |
| `DELETE /api/github/oauth/token` | Invalidates current token, basically the equivalent of a logout. Must authenticate using token in `Authorization` header. |
| `DELETE /api/github/oauth/grant` | Revokes the user's grant, basically the equivalent of an uninstall. must authenticate using token in `Authorization` header. |
| Route | Route Description |
| --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `GET /api/github/oauth/login` | Redirects to GitHub's authorization endpoint. Accepts optional `?state` and `?scopes` query parameters. `?scopes` is a comma-separated list of [supported OAuth scope names](https://docs.github.com/en/developers/apps/scopes-for-oauth-apps#available-scopes) |
| `GET /api/github/oauth/callback` | The client's redirect endpoint. This is where the `token` event gets triggered |
| `POST /api/github/oauth/token` | Exchange an authorization code for an OAuth Access token. If successful, the `token` event gets triggered. |
| `GET /api/github/oauth/token` | Check if token is valid. Must authenticate using token in `Authorization` header. Uses GitHub's [`POST /applications/{client_id}/token`](https://docs.github.com/en/rest/reference/apps#check-a-token) endpoint |
| `PATCH /api/github/oauth/token` | Resets a token (invalidates current one, returns new token). Must authenticate using token in `Authorization` header. Uses GitHub's [`PATCH /applications/{client_id}/token`](https://docs.github.com/en/rest/reference/apps#reset-a-token) endpoint. |
| `PATCH /api/github/oauth/refresh-token` | Refreshes an expiring token (invalidates current one, returns new access token and refresh token). Must authenticate using token in `Authorization` header. Uses GitHub's [`POST https://github.com/login/oauth/access_token`](https://docs.github.com/en/developers/apps/refreshing-user-to-server-access-tokens#renewing-a-user-token-with-a-refresh-token) OAuth endpoint. |
| `POST /api/github/oauth/token/scoped` | Creates a scoped token (does not invalidate the current one). Must authenticate using token in `Authorization` header. Uses GitHub's [`POST /applications/{client_id}/token/scoped`](https://docs.github.com/en/rest/reference/apps#create-a-scoped-access-token) endpoint. |
| `DELETE /api/github/oauth/token` | Invalidates current token, basically the equivalent of a logout. Must authenticate using token in `Authorization` header. |
| `DELETE /api/github/oauth/grant` | Revokes the user's grant, basically the equivalent of an uninstall. must authenticate using token in `Authorization` header. |
### `getNodeMiddleware(app, options)`
### `createNodeMiddleware(app, options)`

@@ -1215,9 +905,10 @@ Native http server middleware for Node.js

```js
const { OAuthApp, getNodeMiddleware } = require("@octokit/oauth-app");
const { OAuthApp, createNodeMiddleware } = require("@octokit/oauth-app");
const app = new OAuthApp({
clientId: "0123",
clientSecret: "0123secret",
clientType: "oauth-app",
clientId: "1234567890abcdef1234",
clientSecret: "1234567890abcdef1234567890abcdef12345678",
});
const middleware = getNodeMiddleware(app, {
const middleware = createNodeMiddleware(app, {
pathPrefix: "/api/github/oauth/",

@@ -1224,0 +915,0 @@ });

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc