@logto/connector-github 1.5.1 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,63 +1,160 @@
1
1
  # Github connector
2
2
 
3
- The official Logto connector for GitHub social sign-in.
3
+ Integrate GitHub OAuth app to enable Sign-in with GitHub, account linking, and secure access to GitHub APIs.
4
4
 
5
5
  **Table of contents**
6
6
 
7
7
  - [Github connector](#github-connector)
8
8
  - [Get started](#get-started)
9
- - [Sign in with GitHub account](#sign-in-with-github-account)
10
- - [Create and configure OAuth app](#create-and-configure-oauth-app)
11
- - [Managing OAuth apps](#managing-oauth-apps)
12
- - [Configure your connector](#configure-your-connector)
13
- - [Config types](#config-types)
14
- - [Test GitHub connector](#test-github-connector)
9
+ - [Step 1: Create an OAuth app on GitHub](#step-1-create-an-oauth-app-on-github)
10
+ - [Step 2: Configure your Logto connector](#step-2-configure-your-logto-connector)
11
+ - [Step 3: Configure scopes (Optional)](#step-3-configure-scopes-optional)
12
+ - [Step 4: General settings](#step-4-general-settings)
13
+ - [Step 5: Test your integration (Optional)](#step-5-test-your-integration-optional)
14
+ - [Utilize the GitHub connector](#utilize-the-github-connector)
15
+ - [Manage user's GitHub identity](#manage-users-github-identity)
15
16
  - [Reference](#reference)
16
17
 
17
18
  ## Get started
18
19
 
19
- The GitHub connector enables end-users to sign in to your application using their own GitHub accounts via GitHub OAuth 2.0 authentication protocol.
20
+ The GitHub connector enables OAuth 2.0 integration to let your application:
20
21
 
21
- ## Sign in with GitHub account
22
+ - Add "Sign-in with GitHub" authentication
23
+ - Link user accounts to GitHub identities
24
+ - Sync user profile info from GitHub
25
+ - Access GitHub APIs through secure token storage in Logto [Secret Vault](https://docs.logto.io/secret-vault/federated-token-set) for automation tasks (e.g., creating GitHub issues, managing repositories from your app)
22
26
 
23
- Go to the [GitHub website](https://github.com/) and sign in with your GitHub account. You may register a new account if you don't have one.
27
+ ## Step 1: Create an OAuth app on GitHub
24
28
 
25
- ## Create and configure OAuth app
29
+ Before you can use GitHub as an authentication provider, you must create an OAuth App on GitHub to obtain OAuth 2.0 credentials.
26
30
 
27
- Follow the [creating an OAuth App](https://docs.github.com/en/developers/apps/building-oauth-apps/creating-an-oauth-app) guide, and register a new application.
31
+ 1. Go to [GitHub](https://github.com/) and sign in with your account, or create a new account if needed.
32
+ 2. Navigate to [Settings > Developer settings > OAuth apps](https://github.com/settings/developers).
33
+ 3. Click **New OAuth App** to register a new application:
34
+ - **Application name**: Enter a descriptive name for your app.
35
+ - **Homepage URL**: Enter your application's homepage URL.
36
+ - **Authorization callback URL**: Copy the **Callback URI** from your Logto GitHub connector and paste it here. After users sign in with GitHub, they'll be redirected here with an authorization code that Logto uses to complete authentication.
37
+ - **Application description**: (Optional) Add a brief description of your app.
38
+ 4. Click **Register application** to create the OAuth App.
28
39
 
29
- Name your new OAuth application in **Application name** and fill up **Homepage URL** of the app.
30
- You can leave **Application description** field blank and customize **Authorization callback URL** as `${your_logto_origin}/callback/${connector_id}`. The `connector_id` can be found on the top bar of the Logto Admin Console connector details page.
40
+ **Note**:
31
41
 
32
- > Note: If you encounter the error message "The redirect_uri MUST match the registered callback URL for this application." when logging in, try aligning the Authorization Callback URL of your GitHub OAuth App and your Logto App's redirect URL (of course, including the protocol) to resolve the issue.
42
+ We suggest not checking the box for **Enable Device Flow**, as users who sign in with GitHub on mobile devices would need to confirm the initial sign-in action in the GitHub mobile app. Many GitHub users do not install the GitHub mobile app on their phones, which could block the sign-in flow. Only enable this if you expect end-users to confirm their sign-in flow through the GitHub mobile app. See details about [device flow](https://docs.github.com/en/developers/apps/building-oauth-apps/authorizing-oauth-apps#device-flow).
33
43
 
34
- We suggest not to check the box before **Enable Device Flow**, or users who sign in with GitHub on mobile devices must confirm the initial sign-in action in the GitHub app. Many GitHub users do not install the GitHub mobile app on their phones, which could block the sign-in flow. Please ignore our suggestion if you are expecting end-users to confirm their sign-in flow. See details of [device flow](https://docs.github.com/en/developers/apps/building-oauth-apps/authorizing-oauth-apps#device-flow).
44
+ For more details on setting up GitHub OAuth Apps, see [Creating an OAuth App](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/creating-an-oauth-app).
35
45
 
36
- ## Managing OAuth apps
46
+ ## Step 2: Configure your Logto connector
37
47
 
38
- Go to the [OAuth Apps page](https://github.com/settings/developers) and you can add, edit or delete existing OAuth apps.
39
- You can also find `Client ID` and generate `Client secrets` in OAuth app detail pages.
48
+ After creating the OAuth app in GitHub, you'll be redirected to a details page where you can copy the Client ID and generate a Client secret.
40
49
 
41
- ## Configure your connector
50
+ 1. Copy the **Client ID** from your GitHub OAuth app and paste it into the `clientId` field in Logto.
51
+ 2. Click **Generate a new client secret** in GitHub to create a new secret, then copy and paste it into the `clientSecret` field in Logto.
52
+ 3. Click **Save and Done** in Logto to connect your identity system with GitHub.
42
53
 
43
- Fill out the `clientId` and `clientSecret` field with _Client ID_ and _Client Secret_ you've got from OAuth app detail pages mentioned in the previous section.
54
+ **Warning**: Keep your Client secret secure and never expose it in client-side code. GitHub client secrets cannot be recovered if lost - you'll need to generate a new one.
44
55
 
45
- `scope` is a space-delimited list of [scopes](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/scopes-for-oauth-apps). If not provided, scope defaults to be `read:user`.
56
+ ## Step 3: Configure scopes (Optional)
46
57
 
47
- ### Config types
58
+ Scopes define the permissions your app requests from users and control which data your app can access from their GitHub accounts.
48
59
 
49
- | Name | Type |
50
- |--------------|--------|
51
- | clientId | string |
52
- | clientSecret | string |
53
- | scope | string |
60
+ Use the `Scopes` field in Logto to request extra permissions from GitHub. Choose one of the following approaches based on your needs:
54
61
 
62
+ ### Option 1: No extra API scopes needed
55
63
 
56
- ## Test GitHub connector
64
+ - Leave the `Scopes` field in your Logto GitHub connector blank.
65
+ - The default scope `read:user` will be requested to ensure Logto can get basic user info (e.g., email, name, avatar) properly.
57
66
 
58
- That's it. The GitHub connector should be available now. Don't forget to [Enable connector in sign-in experience](https://docs.logto.io/docs/recipes/configure-connectors/social-connector/enable-social-sign-in/).
67
+ ### Option 2: Request additional scopes at sign-in
68
+
69
+ - Browse all available [GitHub scopes for OAuth apps](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/scopes-for-oauth-apps) and add only the scopes your app needs.
70
+ - Enter all desired scopes in the **Scopes** field, separated by spaces.
71
+ - Any scopes you list here override the defaults, so always include the authentication scope: `read:user`.
72
+ - Common additional scopes include:
73
+ - `repo`: Full control of private repositories
74
+ - `public_repo`: Access to public repositories
75
+ - `user:email`: Access to user email addresses
76
+ - `notifications`: Access to notifications
77
+ - Ensure all scopes are spelled correctly and valid. An incorrect or unsupported scope will result in an "Invalid scope" error from GitHub.
78
+
79
+ ### Option 3: Request incremental scopes later
80
+
81
+ - After the user signs in, you can [request additional scopes](https://docs.logto.io/secret-vault/federated-token-set#reauthentication-and-token-renewal) on demand by reinitiating a federated social authorization flow and updating users' stored token set.
82
+ - These additional scopes do not need to be filled in the `Scopes` field in your Logto GitHub connector, and can be achieved through Logto's Social Verification API.
83
+
84
+ By following these steps, your Logto GitHub connector requests exactly the permissions your app needs - no more, no less.
85
+
86
+ **Tip**: If your app requests these scopes to access the GitHub API and perform actions, make sure to enable **Store tokens for persistent API access** in Logto GitHub connector. See the next section for details.
87
+
88
+ ## Step 4: General settings
89
+
90
+ Here are some general settings that won't block the connection to GitHub but may affect the end-user authentication experience.
91
+
92
+ ### Sync profile information
93
+
94
+ In the GitHub connector, you can set the policy for syncing profile information, such as user names and avatars. Choose from:
95
+
96
+ - **Only sync at sign-up**: Profile info is fetched once when the user first signs in.
97
+ - **Always sync at sign-in**: Profile info is updated every time the user signs in.
98
+
99
+ ### Store tokens to access GitHub APIs (Optional)
100
+
101
+ If you want to access GitHub APIs and perform actions with user authorization (whether via social sign-in or account linking), Logto needs to get specific API scopes and store tokens.
102
+
103
+ 1. Add the required scopes following the instructions above.
104
+ 2. Enable **Store tokens for persistent API access** in the Logto GitHub connector. Logto will securely store GitHub access tokens in the [Secret Vault](https://docs.logto.io/secret-vault/federated-token-set).
105
+
106
+ **Note**:
107
+
108
+ When using a GitHub **OAuth App** as described in this tutorial, you cannot get a refresh token from GitHub because its access token does not expire unless the user manually revokes it. Therefore, you do not need to add `offline_access` in the `Scopes` field — doing so may cause an error.
109
+
110
+ If you want the access token to expire or use refresh tokens, consider integrating with a **GitHub App** instead. Learn about the [differences between GitHub Apps and OAuth Apps](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/differences-between-github-apps-and-oauth-apps).
111
+
112
+ ## Step 5: Test your integration (Optional)
113
+
114
+ Before going live, test your GitHub integration:
115
+
116
+ 1. Use the connector in a Logto development tenant.
117
+ 2. Verify that users can sign in with GitHub.
118
+ 3. Check that the correct scopes are being requested.
119
+ 4. Test API calls if you're storing tokens.
120
+
121
+ GitHub OAuth Apps work with any GitHub user account immediately - there's no need for test users or app approval like some other platforms.
122
+
123
+ ## Utilize the GitHub connector
124
+
125
+ Once you've created a GitHub connector and connected it to GitHub, you can incorporate it into your end-user flows. Choose the options that match your needs:
126
+
127
+ ### Enable "Sign-in with GitHub"
128
+
129
+ 1. In Logto Console, go to [Sign-in experience > Sign-up and sign-in](https://cloud.logto.io/to/sign-in-experience/sign-up-and-sign-in).
130
+ 2. Add the GitHub connector under **Social sign-in** section to let users authenticate with GitHub.
131
+
132
+ Learn more about [social sign-in experience](https://docs.logto.io//end-user-flows/sign-up-and-sign-in/social-sign-in).
133
+
134
+ ### Link or unlink a GitHub account
135
+
136
+ Use the Account API to build a custom Account Center in your app that lets signed-in users link or unlink their GitHub account. [Follow the Account API tutorial](https://docs.logto.io//end-user-flows/account-settings/by-account-api#link-a-new-social-connection)
137
+
138
+ **Tip**: It's allowed to enable the GitHub connector only for account linking and API access, without enabling it for social sign-in.
139
+
140
+ ### Access GitHub APIs and perform actions
141
+
142
+ Your application can retrieve stored GitHub access tokens from the Secret Vault to call GitHub APIs and automate backend tasks (for example, creating issues, managing repositories, or automating workflows). Refer to the guide on retrieving stored tokens for API access.
143
+
144
+ ## Manage user's GitHub identity
145
+
146
+ After a user links their GitHub account, admins can manage that connection in the Logto Console:
147
+
148
+ 1. Navigate to [Logto console > User management](https://cloud.logto.io/to/users) and open the user's profile.
149
+ 2. Under **Social connections**, locate the GitHub item and click **Manage**.
150
+ 3. On this page, admins can manage the user's GitHub connection, see all profile information granted and synced from their GitHub account, and check the [access token status](https://docs.logto.io/secret-vault/federated-token-set#token-storage-status).
151
+
152
+ **Note**: GitHub's access token response does not include the specific scope information, so Logto cannot directly display the list of permissions granted by the user. However, as long as the user has consented to the requested scopes during authorization, your application will have the corresponding permissions when accessing the GitHub API.
59
153
 
60
154
  ## Reference
61
155
 
62
- - [GitHub - Developers - Apps](https://docs.github.com/en/developers/apps/getting-started-with-apps/about-apps)
63
- - [GitHub - Developers - Apps - Creating an OAuth App](https://docs.github.com/en/developers/apps/building-oauth-apps/creating-an-oauth-app)
156
+ [GitHub Developer Documentation - About Apps](https://docs.github.com/en/developers/apps/getting-started-with-apps/about-apps)
157
+
158
+ [GitHub Developer Documentation - Creating an OAuth App](https://docs.github.com/en/developers/apps/building-oauth-apps/creating-an-oauth-app)
159
+
160
+ [GitHub OAuth App Scopes Documentation](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/scopes-for-oauth-apps)
package/lib/index.js CHANGED
@@ -52,13 +52,14 @@ var defaultMetadata = {
52
52
  },
53
53
  {
54
54
  key: "scope",
55
- type: ConnectorConfigFormItemType.Text,
55
+ type: ConnectorConfigFormItemType.MultilineText,
56
56
  label: "Scope",
57
57
  required: false,
58
- placeholder: "<scope>",
59
- description: "The `scope` determines permissions granted by the user's authorization. If you are not sure what to enter, do not worry, just leave it blank."
58
+ placeholder: "Enter the scopes (separated by a space)",
59
+ description: "The `scope` determines permissions granted by the user's authorization. "
60
60
  }
61
- ]
61
+ ],
62
+ isTokenStorageSupported: true
62
63
  };
63
64
  var defaultTimeout = 5e3;
64
65
 
@@ -78,7 +79,9 @@ var emailAddressGuard = z.object({
78
79
  var accessTokenResponseGuard = z.object({
79
80
  access_token: z.string(),
80
81
  scope: z.string(),
81
- token_type: z.string()
82
+ token_type: z.string(),
83
+ refresh_token: z.string().optional(),
84
+ expires_in: z.number().optional()
82
85
  });
83
86
  var userInfoResponseGuard = z.object({
84
87
  id: z.number(),
@@ -94,14 +97,14 @@ var authorizationCallbackErrorGuard = z.object({
94
97
  var authResponseGuard = z.object({ code: z.string() });
95
98
 
96
99
  // src/index.ts
97
- var getAuthorizationUri = (getConfig) => async ({ state, redirectUri }) => {
100
+ var getAuthorizationUri = (getConfig) => async ({ state, redirectUri, scope: scope2 }) => {
98
101
  const config = await getConfig(defaultMetadata.id);
99
102
  validateConfig(config, githubConfigGuard);
100
103
  const queryParameters = new URLSearchParams({
101
104
  client_id: config.clientId,
102
105
  redirect_uri: redirectUri,
103
106
  state,
104
- scope: config.scope ?? scope
107
+ scope: scope2 ?? config.scope ?? scope
105
108
  });
106
109
  return `${authorizationEndpoint}?${queryParameters.toString()}`;
107
110
  };
@@ -141,13 +144,34 @@ var getAccessToken = async (config, codeObject) => {
141
144
  }
142
145
  const { access_token: accessToken } = result.data;
143
146
  assert(accessToken, new ConnectorError(ConnectorErrorCodes.SocialAuthCodeInvalid));
144
- return { accessToken };
147
+ return result.data;
145
148
  };
146
- var getUserInfo = (getConfig) => async (data) => {
149
+ var _getAccessTokenByRefreshToken = async (config, refreshToken) => {
150
+ const { clientId: client_id, clientSecret: client_secret } = config;
151
+ const httpResponse = await ky.post(accessTokenEndpoint, {
152
+ body: new URLSearchParams({
153
+ client_id,
154
+ client_secret,
155
+ refresh_token: refreshToken,
156
+ grant_type: "refresh_token"
157
+ }),
158
+ timeout: defaultTimeout
159
+ }).json();
160
+ const result = accessTokenResponseGuard.safeParse(httpResponse);
161
+ if (!result.success) {
162
+ throw new ConnectorError(ConnectorErrorCodes.InvalidResponse, result.error);
163
+ }
164
+ const { access_token } = result.data;
165
+ assert(access_token, new ConnectorError(ConnectorErrorCodes.SocialAuthCodeInvalid));
166
+ return result.data;
167
+ };
168
+ var handleAuthorizationCallback = async (getConfig, data) => {
147
169
  const { code } = await authorizationCallbackHandler(data);
148
170
  const config = await getConfig(defaultMetadata.id);
149
171
  validateConfig(config, githubConfigGuard);
150
- const { accessToken } = await getAccessToken(config, { code });
172
+ return getAccessToken(config, { code });
173
+ };
174
+ var _getUserInfo = async (accessToken) => {
151
175
  const authedApi = ky.create({
152
176
  timeout: defaultTimeout,
153
177
  hooks: {
@@ -195,13 +219,40 @@ var getUserInfo = (getConfig) => async (data) => {
195
219
  throw error;
196
220
  }
197
221
  };
222
+ var getTokenResponseAndUserInfo = (getConfig) => async (data) => {
223
+ const tokenResponse = await handleAuthorizationCallback(getConfig, data);
224
+ const userInfo = await _getUserInfo(tokenResponse.access_token);
225
+ return {
226
+ tokenResponse,
227
+ userInfo
228
+ };
229
+ };
230
+ var getUserInfo = (getConfig) => async (data) => {
231
+ const { access_token: accessToken } = await handleAuthorizationCallback(getConfig, data);
232
+ return _getUserInfo(accessToken);
233
+ };
234
+ var getAccessTokenByRefreshToken = (getConfig) => async (refreshToken) => {
235
+ const config = await getConfig(defaultMetadata.id);
236
+ validateConfig(config, githubConfigGuard);
237
+ try {
238
+ return await _getAccessTokenByRefreshToken(config, refreshToken);
239
+ } catch (error) {
240
+ if (error instanceof HTTPError) {
241
+ const { body: rawBody } = error.response;
242
+ throw new ConnectorError(ConnectorErrorCodes.General, JSON.stringify(rawBody));
243
+ }
244
+ throw error;
245
+ }
246
+ };
198
247
  var createGithubConnector = async ({ getConfig }) => {
199
248
  return {
200
249
  metadata: defaultMetadata,
201
250
  type: ConnectorType.Social,
202
251
  configGuard: githubConfigGuard,
203
252
  getAuthorizationUri: getAuthorizationUri(getConfig),
204
- getUserInfo: getUserInfo(getConfig)
253
+ getUserInfo: getUserInfo(getConfig),
254
+ getTokenResponseAndUserInfo: getTokenResponseAndUserInfo(getConfig),
255
+ getAccessTokenByRefreshToken: getAccessTokenByRefreshToken(getConfig)
205
256
  };
206
257
  };
207
258
  var index_default = createGithubConnector;
package/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/constant.ts","../src/types.ts"],"sourcesContent":["import { assert, conditional, trySafe } from '@silverhand/essentials';\n\nimport {\n ConnectorError,\n ConnectorErrorCodes,\n validateConfig,\n ConnectorType,\n jsonGuard,\n} from '@logto/connector-kit';\nimport type {\n GetAuthorizationUri,\n GetUserInfo,\n SocialConnector,\n CreateConnector,\n GetConnectorConfig,\n} from '@logto/connector-kit';\nimport ky, { HTTPError } from 'ky';\n\nimport {\n authorizationEndpoint,\n accessTokenEndpoint,\n scope as defaultScope,\n userInfoEndpoint,\n userEmailsEndpoint,\n defaultMetadata,\n defaultTimeout,\n} from './constant.js';\nimport type { GithubConfig } from './types.js';\nimport {\n authorizationCallbackErrorGuard,\n githubConfigGuard,\n emailAddressGuard,\n accessTokenResponseGuard,\n userInfoResponseGuard,\n authResponseGuard,\n} from './types.js';\n\nconst getAuthorizationUri =\n (getConfig: GetConnectorConfig): GetAuthorizationUri =>\n async ({ state, redirectUri }) => {\n const config = await getConfig(defaultMetadata.id);\n validateConfig(config, githubConfigGuard);\n const queryParameters = new URLSearchParams({\n client_id: config.clientId,\n redirect_uri: redirectUri,\n state,\n scope: config.scope ?? defaultScope,\n });\n\n return `${authorizationEndpoint}?${queryParameters.toString()}`;\n };\n\nconst authorizationCallbackHandler = async (parameterObject: unknown) => {\n const result = authResponseGuard.safeParse(parameterObject);\n\n if (result.success) {\n return result.data;\n }\n\n const parsedError = authorizationCallbackErrorGuard.safeParse(parameterObject);\n\n if (!parsedError.success) {\n throw new ConnectorError(ConnectorErrorCodes.General, JSON.stringify(parameterObject));\n }\n\n const { error, error_description, error_uri } = parsedError.data;\n\n if (error === 'access_denied') {\n throw new ConnectorError(ConnectorErrorCodes.AuthorizationFailed, error_description);\n }\n\n throw new ConnectorError(ConnectorErrorCodes.General, {\n error,\n errorDescription: error_description,\n error_uri,\n });\n};\n\nexport const getAccessToken = async (config: GithubConfig, codeObject: { code: string }) => {\n const { code } = codeObject;\n const { clientId: client_id, clientSecret: client_secret } = config;\n\n const httpResponse = await ky\n .post(accessTokenEndpoint, {\n body: new URLSearchParams({\n client_id,\n client_secret,\n code,\n }),\n timeout: defaultTimeout,\n })\n .json();\n\n const result = accessTokenResponseGuard.safeParse(httpResponse);\n\n if (!result.success) {\n throw new ConnectorError(ConnectorErrorCodes.InvalidResponse, result.error);\n }\n\n const { access_token: accessToken } = result.data;\n\n assert(accessToken, new ConnectorError(ConnectorErrorCodes.SocialAuthCodeInvalid));\n\n return { accessToken };\n};\n\nconst getUserInfo =\n (getConfig: GetConnectorConfig): GetUserInfo =>\n async (data) => {\n const { code } = await authorizationCallbackHandler(data);\n const config = await getConfig(defaultMetadata.id);\n validateConfig(config, githubConfigGuard);\n const { accessToken } = await getAccessToken(config, { code });\n\n const authedApi = ky.create({\n timeout: defaultTimeout,\n hooks: {\n beforeRequest: [\n (request) => {\n request.headers.set('Authorization', `Bearer ${accessToken}`);\n },\n ],\n },\n });\n\n try {\n /**\n * If user(s) is using GitHub Apps (instead of OAuth Apps), they can customize\n * \"Account permissions\" and restrict the \"email addresses\" visibility, and GitHub\n * hence throws error instead of returning an empty array.\n *\n * We try catch the error and return an empty array instead.\n */\n const [userInfo, userEmails = []] = await Promise.all([\n authedApi.get(userInfoEndpoint).json(),\n trySafe(authedApi.get(userEmailsEndpoint).json()),\n ]);\n\n const userInfoResult = userInfoResponseGuard.safeParse(userInfo);\n const userEmailsResult = emailAddressGuard.array().safeParse(userEmails);\n\n if (!userInfoResult.success) {\n throw new ConnectorError(ConnectorErrorCodes.InvalidResponse, userInfoResult.error);\n }\n\n if (!userEmailsResult.success) {\n throw new ConnectorError(ConnectorErrorCodes.InvalidResponse, userEmailsResult.error);\n }\n\n const { id, avatar_url: avatar, email: publicEmail, name } = userInfoResult.data;\n\n return {\n id: String(id),\n avatar: conditional(avatar),\n email: conditional(\n publicEmail ??\n userEmailsResult.data.find(({ verified, primary }) => verified && primary)?.email\n ),\n name: conditional(name),\n rawData: jsonGuard.parse({\n userInfo,\n userEmails,\n }),\n };\n } catch (error: unknown) {\n if (error instanceof HTTPError) {\n const { status, body: rawBody } = error.response;\n\n if (status === 401) {\n throw new ConnectorError(ConnectorErrorCodes.SocialAccessTokenInvalid);\n }\n\n throw new ConnectorError(ConnectorErrorCodes.General, JSON.stringify(rawBody));\n }\n\n throw error;\n }\n };\n\nconst createGithubConnector: CreateConnector<SocialConnector> = async ({ getConfig }) => {\n return {\n metadata: defaultMetadata,\n type: ConnectorType.Social,\n configGuard: githubConfigGuard,\n getAuthorizationUri: getAuthorizationUri(getConfig),\n getUserInfo: getUserInfo(getConfig),\n };\n};\n\nexport default createGithubConnector;\n","import type { ConnectorMetadata } from '@logto/connector-kit';\nimport { ConnectorPlatform, ConnectorConfigFormItemType } from '@logto/connector-kit';\n\nexport const authorizationEndpoint = 'https://github.com/login/oauth/authorize';\n/**\n * `read:user` read user profile data; `user:email` read user email addresses (including private email addresses).\n * Ref: https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/scopes-for-oauth-apps\n */\nexport const scope = 'read:user user:email';\nexport const accessTokenEndpoint = 'https://github.com/login/oauth/access_token';\nexport const userInfoEndpoint = 'https://api.github.com/user';\n// Ref: https://docs.github.com/en/rest/users/emails?apiVersion=2022-11-28#list-email-addresses-for-the-authenticated-user\nexport const userEmailsEndpoint = 'https://api.github.com/user/emails';\n\nexport const defaultMetadata: ConnectorMetadata = {\n id: 'github-universal',\n target: 'github',\n platform: ConnectorPlatform.Universal,\n name: {\n en: 'GitHub',\n 'zh-CN': 'GitHub',\n 'tr-TR': 'GitHub',\n ko: 'GitHub',\n },\n logo: './logo.svg',\n logoDark: './logo-dark.svg',\n description: {\n en: 'GitHub is an online community for software development and version control.',\n 'zh-CN': 'GitHub 是极受欢迎的代码托管仓库。',\n 'tr-TR': 'GitHub, yazılım geliştirme ve sürüm kontrolü için çevrimiçi bir topluluktur.',\n ko: 'GitHub는 소프트웨어 개발과 버전 관리를 위한 온라인 커뮤니티입니다.',\n },\n readme: './README.md',\n formItems: [\n {\n key: 'clientId',\n type: ConnectorConfigFormItemType.Text,\n label: 'Client ID',\n required: true,\n placeholder: '<client-id>',\n },\n {\n key: 'clientSecret',\n type: ConnectorConfigFormItemType.Text,\n label: 'Client Secret',\n required: true,\n placeholder: '<client-secret>',\n },\n {\n key: 'scope',\n type: ConnectorConfigFormItemType.Text,\n label: 'Scope',\n required: false,\n placeholder: '<scope>',\n description:\n \"The `scope` determines permissions granted by the user's authorization. If you are not sure what to enter, do not worry, just leave it blank.\",\n },\n ],\n};\n\nexport const defaultTimeout = 5000;\n","import { z } from 'zod';\n\nexport const githubConfigGuard = z.object({\n clientId: z.string(),\n clientSecret: z.string(),\n scope: z.string().optional(),\n});\n\nexport type GithubConfig = z.infer<typeof githubConfigGuard>;\n\n/**\n * This guard is used to validate the response from the GitHub API when requesting the user's email addresses.\n * Ref: https://docs.github.com/en/rest/users/emails?apiVersion=2022-11-28#list-email-addresses-for-the-authenticated-user\n */\nexport const emailAddressGuard = z.object({\n email: z.string(),\n primary: z.boolean(),\n verified: z.boolean(),\n visibility: z.string().nullable(),\n});\n\nexport const accessTokenResponseGuard = z.object({\n access_token: z.string(),\n scope: z.string(),\n token_type: z.string(),\n});\n\nexport type AccessTokenResponse = z.infer<typeof accessTokenResponseGuard>;\n\nexport const userInfoResponseGuard = z.object({\n id: z.number(),\n avatar_url: z.string().optional().nullable(),\n email: z.string().optional().nullable(),\n name: z.string().optional().nullable(),\n});\n\nexport type UserInfoResponse = z.infer<typeof userInfoResponseGuard>;\n\nexport const authorizationCallbackErrorGuard = z.object({\n error: z.string(),\n error_description: z.string(),\n error_uri: z.string(),\n});\n\nexport const authResponseGuard = z.object({ code: z.string() });\n"],"mappings":";AAAA,SAAS,QAAQ,aAAa,eAAe;AAE7C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA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ACV,MAAM,cAAc;AAAA,IACpB,aAAa;AAAA,IACb,qBAAqB,oBAAoB,SAAS;AAAA,IAClD,aAAa,YAAY,SAAS;AAAA,EACpC;AACF;AAEA,IAAO,gBAAQ;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts","../src/constant.ts","../src/types.ts"],"sourcesContent":["import { assert, conditional, trySafe } from '@silverhand/essentials';\n\nimport {\n ConnectorError,\n ConnectorErrorCodes,\n validateConfig,\n ConnectorType,\n jsonGuard,\n} from '@logto/connector-kit';\nimport type {\n GetAuthorizationUri,\n GetUserInfo,\n SocialConnector,\n CreateConnector,\n GetConnectorConfig,\n GetTokenResponseAndUserInfo,\n GetAccessTokenByRefreshToken,\n} from '@logto/connector-kit';\nimport ky, { HTTPError } from 'ky';\n\nimport {\n authorizationEndpoint,\n accessTokenEndpoint,\n scope as defaultScope,\n userInfoEndpoint,\n userEmailsEndpoint,\n defaultMetadata,\n defaultTimeout,\n} from './constant.js';\nimport type { GithubConfig } from './types.js';\nimport {\n authorizationCallbackErrorGuard,\n githubConfigGuard,\n emailAddressGuard,\n accessTokenResponseGuard,\n userInfoResponseGuard,\n authResponseGuard,\n} from './types.js';\n\nconst getAuthorizationUri =\n (getConfig: GetConnectorConfig): GetAuthorizationUri =>\n async ({ state, redirectUri, scope }) => {\n const config = await getConfig(defaultMetadata.id);\n validateConfig(config, githubConfigGuard);\n const queryParameters = new URLSearchParams({\n client_id: config.clientId,\n redirect_uri: redirectUri,\n state,\n scope: scope ?? config.scope ?? defaultScope,\n });\n\n return `${authorizationEndpoint}?${queryParameters.toString()}`;\n };\n\nconst authorizationCallbackHandler = async (parameterObject: unknown) => {\n const result = authResponseGuard.safeParse(parameterObject);\n\n if (result.success) {\n return result.data;\n }\n\n const parsedError = authorizationCallbackErrorGuard.safeParse(parameterObject);\n\n if (!parsedError.success) {\n throw new ConnectorError(ConnectorErrorCodes.General, JSON.stringify(parameterObject));\n }\n\n const { error, error_description, error_uri } = parsedError.data;\n\n if (error === 'access_denied') {\n throw new ConnectorError(ConnectorErrorCodes.AuthorizationFailed, error_description);\n }\n\n throw new ConnectorError(ConnectorErrorCodes.General, {\n error,\n errorDescription: error_description,\n error_uri,\n });\n};\n\nexport const getAccessToken = async (config: GithubConfig, codeObject: { code: string }) => {\n const { code } = codeObject;\n const { clientId: client_id, clientSecret: client_secret } = config;\n\n const httpResponse = await ky\n .post(accessTokenEndpoint, {\n body: new URLSearchParams({\n client_id,\n client_secret,\n code,\n }),\n timeout: defaultTimeout,\n })\n .json();\n\n const result = accessTokenResponseGuard.safeParse(httpResponse);\n\n if (!result.success) {\n throw new ConnectorError(ConnectorErrorCodes.InvalidResponse, result.error);\n }\n\n const { access_token: accessToken } = result.data;\n\n assert(accessToken, new ConnectorError(ConnectorErrorCodes.SocialAuthCodeInvalid));\n\n return result.data;\n};\n\n/**\n * {@link https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/refreshing-user-access-tokens#refreshing-a-user-access-token-with-a-refresh-token}\n */\nconst _getAccessTokenByRefreshToken = async (config: GithubConfig, refreshToken: string) => {\n const { clientId: client_id, clientSecret: client_secret } = config;\n\n const httpResponse = await ky\n .post(accessTokenEndpoint, {\n body: new URLSearchParams({\n client_id,\n client_secret,\n refresh_token: refreshToken,\n grant_type: 'refresh_token',\n }),\n timeout: defaultTimeout,\n })\n .json();\n\n const result = accessTokenResponseGuard.safeParse(httpResponse);\n\n if (!result.success) {\n throw new ConnectorError(ConnectorErrorCodes.InvalidResponse, result.error);\n }\n\n const { access_token } = result.data;\n\n assert(access_token, new ConnectorError(ConnectorErrorCodes.SocialAuthCodeInvalid));\n\n return result.data;\n};\n\nconst handleAuthorizationCallback = async (getConfig: GetConnectorConfig, data: unknown) => {\n const { code } = await authorizationCallbackHandler(data);\n const config = await getConfig(defaultMetadata.id);\n validateConfig(config, githubConfigGuard);\n return getAccessToken(config, { code });\n};\n\nconst _getUserInfo = async (accessToken: string) => {\n const authedApi = ky.create({\n timeout: defaultTimeout,\n hooks: {\n beforeRequest: [\n (request) => {\n request.headers.set('Authorization', `Bearer ${accessToken}`);\n },\n ],\n },\n });\n\n try {\n /**\n * If user(s) is using GitHub Apps (instead of OAuth Apps), they can customize\n * \"Account permissions\" and restrict the \"email addresses\" visibility, and GitHub\n * hence throws error instead of returning an empty array.\n *\n * We try catch the error and return an empty array instead.\n */\n const [userInfo, userEmails = []] = await Promise.all([\n authedApi.get(userInfoEndpoint).json(),\n trySafe(authedApi.get(userEmailsEndpoint).json()),\n ]);\n\n const userInfoResult = userInfoResponseGuard.safeParse(userInfo);\n const userEmailsResult = emailAddressGuard.array().safeParse(userEmails);\n\n if (!userInfoResult.success) {\n throw new ConnectorError(ConnectorErrorCodes.InvalidResponse, userInfoResult.error);\n }\n\n if (!userEmailsResult.success) {\n throw new ConnectorError(ConnectorErrorCodes.InvalidResponse, userEmailsResult.error);\n }\n\n const { id, avatar_url: avatar, email: publicEmail, name } = userInfoResult.data;\n\n return {\n id: String(id),\n avatar: conditional(avatar),\n email: conditional(\n publicEmail ??\n userEmailsResult.data.find(({ verified, primary }) => verified && primary)?.email\n ),\n name: conditional(name),\n rawData: jsonGuard.parse({\n userInfo,\n userEmails,\n }),\n };\n } catch (error: unknown) {\n if (error instanceof HTTPError) {\n const { status, body: rawBody } = error.response;\n\n if (status === 401) {\n throw new ConnectorError(ConnectorErrorCodes.SocialAccessTokenInvalid);\n }\n\n throw new ConnectorError(ConnectorErrorCodes.General, JSON.stringify(rawBody));\n }\n\n throw error;\n }\n};\n\nconst getTokenResponseAndUserInfo =\n (getConfig: GetConnectorConfig): GetTokenResponseAndUserInfo =>\n async (data) => {\n const tokenResponse = await handleAuthorizationCallback(getConfig, data);\n const userInfo = await _getUserInfo(tokenResponse.access_token);\n\n return {\n tokenResponse,\n userInfo,\n };\n };\n\nconst getUserInfo =\n (getConfig: GetConnectorConfig): GetUserInfo =>\n async (data) => {\n const { access_token: accessToken } = await handleAuthorizationCallback(getConfig, data);\n return _getUserInfo(accessToken);\n };\n\nconst getAccessTokenByRefreshToken =\n (getConfig: GetConnectorConfig): GetAccessTokenByRefreshToken =>\n async (refreshToken: string) => {\n const config = await getConfig(defaultMetadata.id);\n validateConfig(config, githubConfigGuard);\n\n try {\n return await _getAccessTokenByRefreshToken(config, refreshToken);\n } catch (error: unknown) {\n if (error instanceof HTTPError) {\n const { body: rawBody } = error.response;\n\n throw new ConnectorError(ConnectorErrorCodes.General, JSON.stringify(rawBody));\n }\n\n throw error;\n }\n };\n\nconst createGithubConnector: CreateConnector<SocialConnector> = async ({ getConfig }) => {\n return {\n metadata: defaultMetadata,\n type: ConnectorType.Social,\n configGuard: githubConfigGuard,\n getAuthorizationUri: getAuthorizationUri(getConfig),\n getUserInfo: getUserInfo(getConfig),\n getTokenResponseAndUserInfo: getTokenResponseAndUserInfo(getConfig),\n getAccessTokenByRefreshToken: getAccessTokenByRefreshToken(getConfig),\n };\n};\n\nexport default createGithubConnector;\n","import type { ConnectorMetadata } from '@logto/connector-kit';\nimport { ConnectorPlatform, ConnectorConfigFormItemType } from '@logto/connector-kit';\n\nexport const authorizationEndpoint = 'https://github.com/login/oauth/authorize';\n/**\n * `read:user` read user profile data; `user:email` read user email addresses (including private email addresses).\n * Ref: https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/scopes-for-oauth-apps\n */\nexport const scope = 'read:user user:email';\nexport const accessTokenEndpoint = 'https://github.com/login/oauth/access_token';\nexport const userInfoEndpoint = 'https://api.github.com/user';\n// Ref: https://docs.github.com/en/rest/users/emails?apiVersion=2022-11-28#list-email-addresses-for-the-authenticated-user\nexport const userEmailsEndpoint = 'https://api.github.com/user/emails';\n\nexport const defaultMetadata: ConnectorMetadata = {\n id: 'github-universal',\n target: 'github',\n platform: ConnectorPlatform.Universal,\n name: {\n en: 'GitHub',\n 'zh-CN': 'GitHub',\n 'tr-TR': 'GitHub',\n ko: 'GitHub',\n },\n logo: './logo.svg',\n logoDark: './logo-dark.svg',\n description: {\n en: 'GitHub is an online community for software development and version control.',\n 'zh-CN': 'GitHub 是极受欢迎的代码托管仓库。',\n 'tr-TR': 'GitHub, yazılım geliştirme ve sürüm kontrolü için çevrimiçi bir topluluktur.',\n ko: 'GitHub는 소프트웨어 개발과 버전 관리를 위한 온라인 커뮤니티입니다.',\n },\n readme: './README.md',\n formItems: [\n {\n key: 'clientId',\n type: ConnectorConfigFormItemType.Text,\n label: 'Client ID',\n required: true,\n placeholder: '<client-id>',\n },\n {\n key: 'clientSecret',\n type: ConnectorConfigFormItemType.Text,\n label: 'Client Secret',\n required: true,\n placeholder: '<client-secret>',\n },\n {\n key: 'scope',\n type: ConnectorConfigFormItemType.MultilineText,\n label: 'Scope',\n required: false,\n placeholder: 'Enter the scopes (separated by a space)',\n description: \"The `scope` determines permissions granted by the user's authorization. \",\n },\n ],\n isTokenStorageSupported: true,\n};\n\nexport const defaultTimeout = 5000;\n","import { z } from 'zod';\n\nexport const githubConfigGuard = z.object({\n clientId: z.string(),\n clientSecret: z.string(),\n scope: z.string().optional(),\n});\n\nexport type GithubConfig = z.infer<typeof githubConfigGuard>;\n\n/**\n * This guard is used to validate the response from the GitHub API when requesting the user's email addresses.\n * Ref: https://docs.github.com/en/rest/users/emails?apiVersion=2022-11-28#list-email-addresses-for-the-authenticated-user\n */\nexport const emailAddressGuard = z.object({\n email: z.string(),\n primary: z.boolean(),\n verified: z.boolean(),\n visibility: z.string().nullable(),\n});\n\nexport const accessTokenResponseGuard = z.object({\n access_token: z.string(),\n scope: z.string(),\n token_type: z.string(),\n refresh_token: z.string().optional(),\n expires_in: z.number().optional(),\n});\n\nexport type AccessTokenResponse = z.infer<typeof accessTokenResponseGuard>;\n\nexport const userInfoResponseGuard = z.object({\n id: z.number(),\n avatar_url: z.string().optional().nullable(),\n email: z.string().optional().nullable(),\n name: z.string().optional().nullable(),\n});\n\nexport type UserInfoResponse = z.infer<typeof userInfoResponseGuard>;\n\nexport const authorizationCallbackErrorGuard = z.object({\n error: z.string(),\n error_description: z.string(),\n error_uri: z.string(),\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B;AACvB,QAAI,iBAAiB,WAAW;AAC9B,YAAM,EAAE,MAAM,QAAQ,IAAI,MAAM;AAEhC,YAAM,IAAI,eAAe,oBAAoB,SAAS,KAAK,UAAU,OAAO,CAAC;AAAA,IAC/E;AAEA,UAAM;AAAA,EACR;AACF;AAEF,IAAM,wBAA0D,OAAO,EAAE,UAAU,MAAM;AACvF,SAAO;AAAA,IACL,UAAU;AAAA,IACV,MAAM,cAAc;AAAA,IACpB,aAAa;AAAA,IACb,qBAAqB,oBAAoB,SAAS;AAAA,IAClD,aAAa,YAAY,SAAS;AAAA,IAClC,6BAA6B,4BAA4B,SAAS;AAAA,IAClE,8BAA8B,6BAA6B,SAAS;AAAA,EACtE;AACF;AAEA,IAAO,gBAAQ;","names":["scope"]}
package/package.json CHANGED
@@ -1,15 +1,15 @@
1
1
  {
2
2
  "name": "@logto/connector-github",
3
- "version": "1.5.1",
3
+ "version": "1.7.0",
4
4
  "description": "Github web connector implementation.",
5
5
  "author": "Silverhand Inc. <contact@silverhand.io>",
6
6
  "dependencies": {
7
- "@logto/connector-kit": "^4.1.1",
8
7
  "@silverhand/essentials": "^2.9.1",
9
8
  "ky": "^1.2.3",
10
9
  "query-string": "^9.0.0",
11
10
  "snakecase-keys": "^8.0.1",
12
- "zod": "^3.23.8"
11
+ "zod": "3.24.3",
12
+ "@logto/connector-kit": "^4.4.0"
13
13
  },
14
14
  "main": "./lib/index.js",
15
15
  "module": "./lib/index.js",
@@ -23,7 +23,7 @@
23
23
  "logo-dark.svg"
24
24
  ],
25
25
  "engines": {
26
- "node": "^20.9.0"
26
+ "node": "^22.14.0"
27
27
  },
28
28
  "eslintConfig": {
29
29
  "extends": "@silverhand",
@@ -44,17 +44,17 @@
44
44
  "devDependencies": {
45
45
  "@silverhand/eslint-config": "6.0.1",
46
46
  "@silverhand/ts-config": "6.0.0",
47
- "@types/node": "^20.11.20",
47
+ "@types/node": "^22.14.0",
48
48
  "@types/supertest": "^6.0.2",
49
- "@vitest/coverage-v8": "^2.1.9",
49
+ "@vitest/coverage-v8": "^3.1.1",
50
50
  "eslint": "^8.56.0",
51
51
  "lint-staged": "^15.0.2",
52
- "nock": "14.0.0-beta.15",
53
- "prettier": "^3.0.0",
52
+ "nock": "^14.0.3",
53
+ "prettier": "^3.5.3",
54
54
  "supertest": "^7.0.0",
55
- "tsup": "^8.3.0",
55
+ "tsup": "^8.5.0",
56
56
  "typescript": "^5.5.3",
57
- "vitest": "^2.1.9"
57
+ "vitest": "^3.1.1"
58
58
  },
59
59
  "scripts": {
60
60
  "precommit": "lint-staged",