Skip to content
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

feat: return and store social connector raw data #5526

Merged
merged 3 commits into from
Mar 21, 2024
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
8 changes: 8 additions & 0 deletions .changeset/gentle-shoes-push.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"@logto/connector-kit": major
---

update `SocialUserInfo` and `GetUserInfo` types

- Added `rawData?: Json` to `SocialUserInfo`
- `GetUserInfo` now does not accept unknown keys in the return object, since the raw data is now stored in `SocialUserInfo`
7 changes: 7 additions & 0 deletions .changeset/new-tables-breathe.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@logto/connector-kit": major
---

guard results of `parseJson` and `parseJsonObject`

Now `parseJson` and `parseJsonObject` are type safe.
21 changes: 21 additions & 0 deletions .changeset/olive-cycles-sip.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
---
"@logto/connector-alipay-native": minor
"@logto/connector-wechat-native": minor
"@logto/connector-mock-social": minor
"@logto/connector-alipay-web": minor
"@logto/connector-feishu-web": minor
"@logto/connector-wechat-web": minor
"@logto/connector-facebook": minor
"@logto/connector-azuread": minor
"@logto/connector-discord": minor
"@logto/connector-github": minor
"@logto/connector-google": minor
"@logto/connector-oauth": minor
"@logto/connector-apple": minor
"@logto/connector-kakao": minor
"@logto/connector-naver": minor
"@logto/connector-wecom": minor
"@logto/connector-oidc": minor
---

return and store social connector raw data
5 changes: 5 additions & 0 deletions .changeset/wild-hotels-drop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@logto/connector-kit": minor
---

add `jsonGuard()` and `jsonObjectGuard()`
2 changes: 1 addition & 1 deletion .gitpod.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ tasks:
cd packages/core
pnpm build
cd -
pnpm connectors:build
pnpm connectors build
pnpm cli connector link
command: |
gp ports await 5432
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"cli": "logto",
"changeset": "changeset",
"alteration": "logto db alt",
"connectors:build": "pnpm -r --filter \"./packages/connectors/connector-*\" build",
"connectors": "pnpm -r --filter \"./packages/connectors/connector-*\"",
"//": "# `changeset version` won't run version lifecycle scripts, see https://github.com/changesets/changesets/issues/860",
"ci:version": "changeset version && pnpm -r version",
"ci:build": "pnpm -r build",
Expand Down
15 changes: 14 additions & 1 deletion packages/connectors/connector-alipay-native/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,10 +156,23 @@ describe('getUserInfo', () => {
sign: '<signature>',
});
const connector = await createConnector({ getConfig });
const { id, name, avatar } = await connector.getUserInfo({ auth_code: 'code' }, jest.fn());
const { id, name, avatar, rawData } = await connector.getUserInfo(
{ auth_code: 'code' },
jest.fn()
);
expect(id).toEqual('2088000000000000');
expect(name).toEqual('PlayboyEric');
expect(avatar).toEqual('https://www.alipay.com/xxx.jpg');
expect(rawData).toEqual({
alipay_user_info_share_response: {
code: '10000',
msg: 'Success',
user_id: '2088000000000000',
nick_name: 'PlayboyEric',
avatar: 'https://www.alipay.com/xxx.jpg',
},
sign: '<signature>',
});
});

it('should throw SocialAccessTokenInvalid with code 20001', async () => {
Expand Down
6 changes: 3 additions & 3 deletions packages/connectors/connector-alipay-native/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,8 +131,8 @@ const getUserInfo =
searchParams: signedSearchParameters,
timeout: { request: defaultTimeout },
});

const result = userInfoResponseGuard.safeParse(parseJson(httpResponse.body));
const rawData = parseJson(httpResponse.body);
const result = userInfoResponseGuard.safeParse(rawData);

if (!result.success) {
throw new ConnectorError(ConnectorErrorCodes.InvalidResponse, result.error);
Expand All @@ -148,7 +148,7 @@ const getUserInfo =
throw new ConnectorError(ConnectorErrorCodes.InvalidResponse);
}

return { id, avatar, name };
return { id, avatar, name, rawData };
};

const errorHandler: ErrorHandler = ({ code, msg, sub_code, sub_msg }) => {
Expand Down
15 changes: 14 additions & 1 deletion packages/connectors/connector-alipay-web/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,10 +142,23 @@ describe('getUserInfo', () => {
sign: '<signature>',
});
const connector = await createConnector({ getConfig });
const { id, name, avatar } = await connector.getUserInfo({ auth_code: 'code' }, jest.fn());
const { id, name, avatar, rawData } = await connector.getUserInfo(
{ auth_code: 'code' },
jest.fn()
);
expect(id).toEqual('2088000000000000');
expect(name).toEqual('PlayboyEric');
expect(avatar).toEqual('https://www.alipay.com/xxx.jpg');
expect(rawData).toEqual({
alipay_user_info_share_response: {
code: '10000',
msg: 'Success',
user_id: '2088000000000000',
nick_name: 'PlayboyEric',
avatar: 'https://www.alipay.com/xxx.jpg',
},
sign: '<signature>',
});
});

it('throw General error if auth_code not provided in input', async () => {
Expand Down
8 changes: 3 additions & 5 deletions packages/connectors/connector-alipay-web/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,10 +130,8 @@ const getUserInfo =
searchParams: signedSearchParameters,
timeout: { request: defaultTimeout },
});

const { body: rawBody } = httpResponse;

const result = userInfoResponseGuard.safeParse(parseJson(rawBody));
const rawData = parseJson(httpResponse.body);
const result = userInfoResponseGuard.safeParse(rawData);

if (!result.success) {
throw new ConnectorError(ConnectorErrorCodes.InvalidResponse, result.error);
Expand All @@ -149,7 +147,7 @@ const getUserInfo =
throw new ConnectorError(ConnectorErrorCodes.InvalidResponse);
}

return { id, avatar, name };
return { id, avatar, name, rawData };
};

const errorHandler: ErrorHandler = ({ code, msg, sub_code, sub_msg }) => {
Expand Down
21 changes: 18 additions & 3 deletions packages/connectors/connector-apple/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,11 @@ describe('getUserInfo', () => {
}));
const connector = await createConnector({ getConfig });
const userInfo = await connector.getUserInfo({ id_token: 'idToken' }, jest.fn());
expect(userInfo).toEqual({ id: userId, email: '[email protected]' });
expect(userInfo).toEqual({
id: userId,
email: '[email protected]',
rawData: { id_token: 'idToken' },
});
});

it('should ignore unverified email', async () => {
Expand All @@ -69,7 +73,7 @@ describe('getUserInfo', () => {
}));
const connector = await createConnector({ getConfig });
const userInfo = await connector.getUserInfo({ id_token: 'idToken' }, jest.fn());
expect(userInfo).toEqual({ id: 'userId' });
expect(userInfo).toEqual({ id: 'userId', rawData: { id_token: 'idToken' } });
});

it('should get user info from the `user` field', async () => {
Expand All @@ -89,7 +93,18 @@ describe('getUserInfo', () => {
jest.fn()
);
// Should use info from `user` field first
expect(userInfo).toEqual({ id: userId, email: '[email protected]', name: 'foo bar' });
expect(userInfo).toEqual({
id: userId,
email: '[email protected]',
name: 'foo bar',
rawData: {
id_token: 'idToken',
user: JSON.stringify({
email: '[email protected]',
name: { firstName: 'foo', lastName: 'bar' },
}),
},
});
});

it('should throw if id token is missing', async () => {
Expand Down
2 changes: 2 additions & 0 deletions packages/connectors/connector-apple/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
ConnectorErrorCodes,
validateConfig,
ConnectorType,
jsonGuard,
} from '@logto/connector-kit';
import { generateStandardId } from '@logto/shared/universal';
import { createRemoteJWKSet, jwtVerify } from 'jose';
Expand Down Expand Up @@ -112,6 +113,7 @@ const getUserInfo =
user?.email ??
(payload.email && payload.email_verified === true ? String(payload.email) : undefined),
name: [user?.name?.firstName, user?.name?.lastName].filter(Boolean).join(' ') || undefined,
rawData: jsonGuard.parse(data),
};
} catch {
throw new ConnectorError(ConnectorErrorCodes.SocialIdTokenInvalid);
Expand Down
12 changes: 8 additions & 4 deletions packages/connectors/connector-azuread/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
"description": "Microsoft Azure AD connector implementation.",
"author": "Mobilist Inc. <[email protected]>",
"dependencies": {
"@logto/connector-kit": "workspace:^2.1.0",
"@azure/msal-node": "^2.0.0"
"@azure/msal-node": "^2.0.0",
"@logto/connector-kit": "workspace:^2.1.0"
},
"main": "./lib/index.js",
"module": "./lib/index.js",
Expand All @@ -26,8 +26,8 @@
"lint": "eslint --ext .ts src",
"lint:report": "pnpm lint --format json --output-file report.json",
"test:only": "NODE_OPTIONS=--experimental-vm-modules jest",
"test": "pnpm build:test && pnpm test:only",
"test:ci": "pnpm test:only --silent --coverage",
"test": "vitest src",
"test:ci": "pnpm run test --silent --coverage",
"prepublishOnly": "pnpm build"
},
"engines": {
Expand All @@ -48,5 +48,9 @@
"prettier": "@silverhand/eslint-config/.prettierrc",
"publishConfig": {
"access": "public"
},
"devDependencies": {
"@vitest/coverage-v8": "^1.4.0",
"vitest": "^1.4.0"
}
}
69 changes: 66 additions & 3 deletions packages/connectors/connector-azuread/src/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,76 @@
import type { GetConnectorConfig } from '@logto/connector-kit';
import nock from 'nock';

import { vi, describe, beforeAll, it, expect } from 'vitest';

import { graphAPIEndpoint } from './constant.js';
import createConnector from './index.js';

const { jest } = import.meta;
vi.mock('@azure/msal-node', async () => ({
ConfidentialClientApplication: class {
async acquireTokenByCode() {
return {
accessToken: 'accessToken',
scopes: ['scopes'],
tokenType: 'tokenType',
};
}
},
}));

const getConnectorConfig = jest.fn() as GetConnectorConfig;
const getConnectorConfig = vi.fn().mockResolvedValue({
clientId: 'clientId',
clientSecret: 'clientSecret',
cloudInstance: 'https://login.microsoftonline.com',
tenantId: 'tenantId',
});

describe('Azure AD connector', () => {
it('init without exploding', () => {
expect(async () => createConnector({ getConfig: getConnectorConfig })).not.toThrow();
});
});

describe('getUserInfo', () => {
beforeAll(async () => {
const graphMeUrl = new URL(graphAPIEndpoint);
nock(graphMeUrl.origin).get(graphMeUrl.pathname).reply(200, {
id: 'id',
displayName: 'displayName',
mail: 'mail',
userPrincipalName: 'userPrincipalName',
});
});

it('should get user info from graph api', async () => {
const connector = await createConnector({ getConfig: getConnectorConfig });
const userInfo = await connector.getUserInfo(
{ code: 'code', redirectUri: 'redirectUri' },
vi.fn()
);
expect(userInfo).toEqual({
id: 'id',
name: 'displayName',
email: 'mail',
rawData: {
id: 'id',
displayName: 'displayName',
mail: 'mail',
userPrincipalName: 'userPrincipalName',
},
});
});

it('should throw if graph api response has no id', async () => {
const graphMeUrl = new URL(graphAPIEndpoint);
nock(graphMeUrl.origin).get(graphMeUrl.pathname).reply(200, {
displayName: 'displayName',
mail: 'mail',
userPrincipalName: 'userPrincipalName',
});

const connector = await createConnector({ getConfig: getConnectorConfig });
const userInfo = connector.getUserInfo({ code: 'code', redirectUri: 'redirectUri' }, vi.fn());
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
await expect(userInfo).rejects.toThrow(expect.objectContaining({ code: 'invalid_response' }));
});
});
12 changes: 4 additions & 8 deletions packages/connectors/connector-azuread/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { got, HTTPError } from 'got';
import path from 'node:path';

import type { AuthorizationCodeRequest, AuthorizationUrlRequest } from '@azure/msal-node';
import { ConfidentialClientApplication, CryptoProvider } from '@azure/msal-node';
import { ConfidentialClientApplication } from '@azure/msal-node';
import type {
GetAuthorizationUri,
GetUserInfo,
Expand Down Expand Up @@ -31,10 +31,6 @@ import {
// eslint-disable-next-line @silverhand/fp/no-let
let authCodeRequest: AuthorizationCodeRequest;

// This `cryptoProvider` seems not used.
// Temporarily keep this as this is a refactor, which should not change the logics.
const cryptoProvider = new CryptoProvider();

const getAuthorizationUri =
(getConfig: GetConnectorConfig): GetAuthorizationUri =>
async ({ state, redirectUri }) => {
Expand Down Expand Up @@ -85,7 +81,6 @@ const getAccessToken = async (config: AzureADConfig, code: string, redirectUri:
});

const authResult = await clientApplication.acquireTokenByCode(codeRequest);

const result = accessTokenResponseGuard.safeParse(authResult);

if (!result.success) {
Expand Down Expand Up @@ -117,8 +112,8 @@ const getUserInfo =
},
timeout: { request: defaultTimeout },
});

const result = userInfoResponseGuard.safeParse(parseJson(httpResponse.body));
const rawData = parseJson(httpResponse.body);
const result = userInfoResponseGuard.safeParse(rawData);

if (!result.success) {
throw new ConnectorError(ConnectorErrorCodes.InvalidResponse, result.error);
Expand All @@ -130,6 +125,7 @@ const getUserInfo =
id,
email: conditional(mail),
name: conditional(displayName),
rawData,
};
} catch (error: unknown) {
if (error instanceof HTTPError) {
Expand Down
9 changes: 8 additions & 1 deletion packages/connectors/connector-discord/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,11 +101,18 @@ describe('Discord connector', () => {
},
jest.fn()
);
expect(socialUserInfo).toMatchObject({
expect(socialUserInfo).toStrictEqual({
id: '1234567890',
name: 'Whumpus',
avatar: 'https://cdn.discordapp.com/avatars/1234567890/avatar_id',
email: '[email protected]',
rawData: {
id: '1234567890',
username: 'Whumpus',
avatar: 'avatar_id',
email: '[email protected]',
verified: true,
},
});
});

Expand Down
Loading
Loading