Skip to content

fix: prevent refreshToken from lost after resetToken #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 30, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
node_version: ["12", "14"]
node_version: ["14"]

steps:
- uses: actions/checkout@v2
Expand Down
30 changes: 18 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,14 @@
- [Standalone usage](#standalone-usage)
- [Usage with Octokit](#usage-with-octokit)
- [`createOAuthUserClientAuth(options)` or `new Octokit({auth})`](#createoauthuserclientauthoptions-or-new-octokitauth)
- [Custom store](#custom-store)
- [Custom request](#custom-request)
- [`auth(command)`](#authcommand)
- [Authentication object](#authentication-object)
- [Session object](#session-object)
- [Authentication object](#authentication-object)
- [OAuth APP authentication token](#oauth-app-authentication-token)
- [GitHub APP user authentication token with expiring disabled](#github-app-user-authentication-token-with-expiring-disabled)
- [GitHub APP user authentication token with expiring enabled](#github-app-user-authentication-token-with-expiring-enabled)
- [`auth.hook(request, route, parameters)` or `auth.hook(request, options)`](#authhookrequest-route-parameters-or-authhookrequest-options)
- [Contributing](#contributing)
- [License](#license)
Expand Down Expand Up @@ -203,17 +209,17 @@ createOAuthAppAuth({

The async `auth()` method returned by `createOAuthUserClientAuth(options)` accepts the following commands:

| Command | `{type: }` | Optional Arguments |
| :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Sign in](https://docs.github.com/en/developers/apps/building-oauth-apps/authorizing-oauth-apps#1-request-a-users-github-identity) | `"signIn"` | <ul><li><code>login: "user"</code></li><li><code>allowSignup: false</code></li><li><code>scopes: ["repo"]</code> (only relevant for OAuth Apps)</li></ul> |
| Get (local) token | `"getToken"` | – |
| [Create an app token](https://docs.github.com/en/developers/apps/building-oauth-apps/authorizing-oauth-apps#2-users-are-redirected-back-to-your-site-by-github) | `"createToken"` | – |
| [Check a token](https://docs.github.com/en/rest/reference/apps#check-a-token) | `"checkToken"` | – |
| [Create a scoped access token](https://docs.github.com/en/rest/reference/apps#create-a-scoped-access-token) (for OAuth App) | `"createScopedToken"` | – |
| [Reset a token](https://docs.github.com/en/rest/reference/apps#reset-a-token) | `"resetToken"` | – |
| [Renewing a user token with a refresh token](https://docs.github.com/en/developers/apps/building-github-apps/reshing-user-to-server-access-tokens#renewing-a-user-token-with-a-refresh-token) (for GitHub App with token expiration enabled) | `"refreshToken"` | – |
| [Delete an app token](https://docs.github.com/en/rest/reference/apps#delete-an-app-token) (sign out) | `"deleteToken"` | `offline: true` (only deletes session from local session store) |
| [Delete an app authorization](https://docs.github.com/en/rest/reference/apps#delete-an-app-authorization) | `"deleteAuthorization"` | – |
| Command | `{type: }` | Optional Arguments |
| :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Sign in](https://docs.github.com/en/developers/apps/building-oauth-apps/authorizing-oauth-apps#1-request-a-users-github-identity) | `"signIn"` | <ul><li><code>login: "user"</code></li><li><code>allowSignup: false</code></li><li><code>scopes: ["repo"]</code> (only relevant for OAuth Apps)</li></ul> |
| Get (local) token | `"getToken"` | – |
| [Create an app token](https://docs.github.com/en/developers/apps/building-oauth-apps/authorizing-oauth-apps#2-users-are-redirected-back-to-your-site-by-github) | `"createToken"` | – |
| [Check a token](https://docs.github.com/en/rest/reference/apps#check-a-token) | `"checkToken"` | – |
| [Create a scoped access token](https://docs.github.com/en/rest/reference/apps#create-a-scoped-access-token) (for OAuth App) | `"createScopedToken"` | – |
| [Reset a token](https://docs.github.com/en/rest/reference/apps#reset-a-token) | `"resetToken"` | – |
| [Renewing a user token with a refresh token](https://docs.github.com/en/developers/apps/building-github-apps/refreshing-user-to-server-access-tokens#renewing-a-user-token-with-a-refresh-token) (for GitHub App with token expiration enabled) | `"refreshToken"` | – |
| [Delete an app token](https://docs.github.com/en/rest/reference/apps#delete-an-app-token) (sign out) | `"deleteToken"` | `offline: true` (only deletes session from local session store) |
| [Delete an app authorization](https://docs.github.com/en/rest/reference/apps#delete-an-app-authorization) | `"deleteAuthorization"` | – |

## Session object

Expand Down
19 changes: 17 additions & 2 deletions src/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,10 @@ export async function auth<
// Auto refresh for user-to-server token.
const expiresAt = this.session.authentication.expiresAt;
if (new Date(expiresAt) > new Date()) return this.session;
// @ts-ignore
return await auth.call(this, { type: "refreshToken" });
return await auth.call(this, { type: "refreshToken" } as Command<
Client,
Expiration
>);
}
}

Expand Down Expand Up @@ -118,6 +120,7 @@ export async function auth<
this.session ||= await auth.call(this);
if (!this.session) throw errors.unauthorized;
}
const oldSession = this.session;

// Prepare payload for `refreshToken` command.
if (this.session && "refreshToken" in this.session.authentication) {
Expand All @@ -133,6 +136,18 @@ export async function auth<
this.session = response.data || null;
}

// Some `oauth-app.js` endpoints (such as `resetToken`) do not (and can
// not) return `refreshToken`. Original `refreshToken` and
// `refreshTokenExpiresAt` are kept to `refreshToken` later.
if (oldSession && "refreshToken" in oldSession.authentication) {
if (this.session && !("refreshToken" in this.session.authentication))
Object.assign(this.session.authentication, {
refreshToken: oldSession.authentication.refreshToken,
refreshTokenExpiresAt:
oldSession.authentication.refreshTokenExpiresAt,
});
}

if (this.sessionStore) await this.sessionStore.set(this.session);
return this.session;
}
Expand Down
52 changes: 52 additions & 0 deletions test/standalone.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -663,4 +663,56 @@ describe("standalone tests under node environment", () => {
expect(sessionStore.set.mock.calls.length).toEqual(1);
expect(sessionStore.set.mock.calls[0][0]).toBeNull();
});

it("keeps refresh token", async () => {
const oldSession = {
authentication: {
token: "token123",
refreshToken: "refreshToken123",
refreshTokenExpiresAt: "2000-01-03T00:00:00.000Z",
},
};
const newSession = { authentication: { token: "token456" } };

const sessionStore = {
get: jest.fn().mockResolvedValue(oldSession),
set: jest.fn().mockResolvedValue(undefined),
};

const fetch = fetchMock
.sandbox()
.patchOnce("http://acme.com/api/github/oauth/token", newSession, {
headers: {
accept: "application/vnd.github.v3+json",
"user-agent": "test",
authorization: "token token123",
},
});

const auth = createOAuthUserClientAuth({
clientId: "clientId123",
sessionStore,
request: request.defaults({
headers: { "user-agent": "test" },
request: { fetch },
}),
});

expect(await auth({ type: "resetToken" })).toEqual({
authentication: {
token: "token456",
refreshToken: "refreshToken123",
refreshTokenExpiresAt: "2000-01-03T00:00:00.000Z",
},
});
expect(sessionStore.get.mock.calls.length).toBe(1);
expect(sessionStore.set.mock.calls.length).toBe(1);
expect(await auth()).toEqual({
authentication: {
token: "token456",
refreshToken: "refreshToken123",
refreshTokenExpiresAt: "2000-01-03T00:00:00.000Z",
},
});
});
});