0
Fork 0
mirror of https://github.com/logto-io/logto.git synced 2025-02-17 22:04:19 -05:00

feat(core): wrap logto/shared and logto/connector-types

This commit is contained in:
Darcy Ye 2022-04-23 16:16:55 +08:00
parent 3c8869150d
commit edf5053581
No known key found for this signature in database
GPG key ID: B46F4C07EDEFC610
15 changed files with 561 additions and 1 deletions

View file

@ -0,0 +1,20 @@
import type { Config } from '@jest/types';
const config: Config.InitialOptions = {
preset: 'ts-jest',
testEnvironment: 'node',
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1',
'^jose/(.*)$': '<rootDir>/node_modules/jose/dist/node/cjs/$1',
},
setupFilesAfterEnv: ['jest-matcher-specific-error'],
coveragePathIgnorePatterns: ['/node_modules/', '/build/'],
coverageReporters: ['text-summary', 'lcov'],
globals: {
'ts-jest': {
tsconfig: 'tsconfig.test.json',
},
},
};
export default config;

View file

@ -0,0 +1,52 @@
{
"name": "@logto/connector-types",
"version": "0.1.0",
"main": "build/index.js",
"author": "Logto Team",
"license": "MPL-2.0",
"files": [
"lib"
],
"private": true,
"scripts": {
"preinstall": "npx only-allow pnpm",
"precommit": "lint-staged",
"build": "rm -rf build/ && tsc --p tsconfig.build.json",
"lint": "eslint --ext .ts src",
"lint:report": "pnpm lint -- --format json --output-file report.json",
"prepack": "pnpm build",
"test": "jest",
"test:coverage": "jest --coverage --silent"
},
"engines": {
"node": ">=14.15.0"
},
"dependencies": {
"@logto/phrases": "^0.1.0",
"@logto/schemas": "^0.1.0",
"got": "^11.8.2",
"jose": "^3.14.3"
},
"devDependencies": {
"@jest/types": "^27.5.1",
"@shopify/jest-koa-mocks": "^3.0.8",
"@silverhand/eslint-config": "^0.10.2",
"@silverhand/essentials": "^1.1.6",
"@silverhand/ts-config": "^0.10.2",
"@types/jest": "^27.4.1",
"eslint": "^8.10.0",
"jest": "^27.5.1",
"jest-matcher-specific-error": "^1.0.0",
"lint-staged": "^11.1.1",
"prettier": "^2.3.2",
"ts-jest": "^27.1.1",
"typescript": "^4.6.2"
},
"eslintConfig": {
"extends": "@silverhand",
"rules": {
"@typescript-eslint/ban-types": "off"
}
},
"prettier": "@silverhand/eslint-config/.prettierrc"
}

View file

@ -0,0 +1,58 @@
import got from 'got';
import { getSignature, request } from './aliyun';
jest.mock('got');
describe('getSignature', () => {
it('should get valid signature', () => {
const parameters = {
AccessKeyId: 'testid',
AccountName: "<a%b'>",
Action: 'SingleSendMail',
AddressType: '1',
Format: 'XML',
HtmlBody: '4',
RegionId: 'cn-hangzhou',
ReplyToAddress: 'true',
SignatureMethod: 'HMAC-SHA1',
SignatureNonce: 'c1b2c332-4cfb-4a0f-b8cc-ebe622aa0a5c',
SignatureVersion: '1.0',
Subject: '3',
TagName: '2',
Timestamp: '2016-10-20T06:27:56Z',
ToAddress: '1@test.com',
Version: '2015-11-23',
};
const signature = getSignature(parameters, 'testsecret', 'POST');
expect(signature).toEqual('llJfXJjBW3OacrVgxxsITgYaYm0=');
});
});
describe('request', () => {
it('should call axios.post with extended params', async () => {
const parameters = {
AccessKeyId: 'testid',
AccountName: "<a%b'>",
Action: 'SingleSendMail',
AddressType: '1',
Format: 'XML',
HtmlBody: '4',
RegionId: 'cn-hangzhou',
ReplyToAddress: 'true',
Subject: '3',
TagName: '2',
ToAddress: '1@test.com',
Version: '2015-11-23',
SignatureMethod: 'HMAC-SHA1',
SignatureVersion: '1.0',
};
await request('http://test.endpoint.com', parameters, 'testsecret');
const calledData = (got.post as jest.MockedFunction<typeof got.post>).mock.calls[0];
expect(calledData).not.toBeUndefined();
const payload = calledData?.[0].form as URLSearchParams;
expect(payload.get('AccessKeyId')).toEqual('testid');
expect(payload.get('Timestamp')).not.toBeNull();
expect(payload.get('SignatureNonce')).not.toBeNull();
expect(payload.get('Signature')).not.toBeNull();
});
});

View file

@ -0,0 +1,82 @@
import { createHmac } from 'crypto';
import { has } from '@silverhand/essentials';
import got from 'got';
export type { Response } from 'got';
// Aliyun has special escape rules.
// https://help.aliyun.com/document_detail/29442.html
const escaper = (string_: string) =>
encodeURIComponent(string_)
.replace(/\*/g, '%2A')
.replace(/'/g, '%27')
.replace(/!/g, '%21')
.replace(/"/g, '%22')
.replace(/\(/g, '%28')
.replace(/\)/g, '%29')
.replace(/\+/, '%2B');
export const getSignature = (
parameters: Record<string, string>,
secret: string,
method: string
) => {
const canonicalizedQuery = Object.keys(parameters)
.slice()
.sort()
.map((key) => {
const value = parameters[key];
return value === undefined ? '' : `${escaper(key)}=${escaper(value)}`;
})
.filter(Boolean)
.join('&');
const stringToSign = `${method.toUpperCase()}&${escaper('/')}&${escaper(canonicalizedQuery)}`;
return createHmac('sha1', `${secret}&`).update(stringToSign).digest('base64');
};
export interface PublicParameters {
AccessKeyId: string;
Format?: string; // 'json' or 'xml', default: 'json'
RegionId?: string; // 'cn-hangzhou' | 'ap-southeast-1' | 'ap-southeast-2'
Signature?: string;
SignatureMethod?: string;
SignatureNonce?: string;
SignatureVersion?: string;
Timestamp?: string;
Version?: string;
}
export const request = async <T>(
url: string,
parameters: PublicParameters & Record<string, string>,
accessKeySecret: string
) => {
const finalParameters: Record<string, string> = {
...parameters,
SignatureNonce: String(Math.random()),
Timestamp: new Date().toISOString(),
};
const signature = getSignature(finalParameters, accessKeySecret, 'POST');
const payload = new URLSearchParams();
for (const key in finalParameters) {
if (has(finalParameters, key)) {
const value = finalParameters[key];
if (value !== undefined) {
payload.append(key, value);
}
}
}
payload.append('Signature', signature);
return got.post<T>({
url,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
form: payload,
});
};

View file

@ -0,0 +1,120 @@
import { Languages } from '@logto/phrases';
import { ArbitraryObject, Connector, ConnectorType } from '@logto/schemas';
import { Response } from './aliyun';
export * from './aliyun';
export interface ConnectorMetadata {
id: string;
type: ConnectorType;
name: Record<Languages, string>;
logo: string;
description: Record<Languages, string>;
readme: string;
configTemplate: string;
}
export interface ConnectorDTO extends Connector {
metadata: ConnectorMetadata;
}
export enum ConnectorErrorCodes {
General,
InsufficientRequestParameters,
InvalidConfig,
InvalidResponse,
TemplateNotFound,
SocialAuthCodeInvalid,
SocialAccessTokenInvalid,
}
export class ConnectorError extends Error {
public code: ConnectorErrorCodes;
constructor(code: ConnectorErrorCodes, message?: string) {
super(message);
this.code = code;
}
}
export type EmailMessageTypes = {
SignIn: {
code: string;
};
Register: {
code: string;
};
ForgotPassword: {
code: string;
};
Test: Record<string, unknown>;
};
type SmsMessageTypes = EmailMessageTypes;
export type SendEmailResponse = { EnvId: string; RequestId: string };
export type SendSmsResponse = { BizId: string; Code: string; Message: string; RequestId: string };
export type EmailSendMessageFunction<
T1 extends ArbitraryObject = ArbitraryObject,
T2 = Response<T1>
> = (
address: string,
type: keyof EmailMessageTypes,
payload: EmailMessageTypes[typeof type]
) => Promise<T2>;
export type SmsSendMessageFunction<
T1 extends ArbitraryObject = ArbitraryObject,
T2 = Response<T1>
> = (
phone: string,
type: keyof SmsMessageTypes,
payload: SmsMessageTypes[typeof type]
) => Promise<T2>;
export interface BaseConnector {
metadata: ConnectorMetadata;
validateConfig: ValidateConfig;
getConfig: GetConnectorConfig;
}
export interface SmsConnector extends BaseConnector {
sendMessage: SmsSendMessageFunction;
}
export interface EmailConnector extends BaseConnector {
sendMessage: EmailSendMessageFunction;
}
export interface SocialConnector extends BaseConnector {
getAuthorizationUri: GetAuthorizationUri;
getAccessToken: GetAccessToken;
getUserInfo: GetUserInfo;
getRequestTimeout?: GetTimeout;
getTimestamp?: GetTimestamp;
}
export type ValidateConfig<T extends ArbitraryObject = ArbitraryObject> = (
config: T
) => Promise<void>;
export type GetAuthorizationUri = (redirectUri: string, state: string) => Promise<string>;
export type AccessTokenObject = { accessToken: string } & Record<string, string>;
export type GetAccessToken = (code: string, redirectUri?: string) => Promise<AccessTokenObject>;
export type GetUserInfo = (
accessTokenObject: AccessTokenObject
) => Promise<{ id: string } & Record<string, string | undefined>>;
export type GetConnectorConfig<T extends ArbitraryObject = ArbitraryObject> = (
id: string
) => Promise<T>;
export type GetTimeout = () => Promise<number>;
export type GetTimestamp = () => string;

View file

@ -0,0 +1,10 @@
{
"extends": "@silverhand/ts-config/tsconfig.base",
"compilerOptions": {
"outDir": "build",
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
}
}

View file

@ -0,0 +1,5 @@
{
"extends": "./tsconfig",
"include": ["src"],
"exclude": ["src/**/*.test.ts"]
}

View file

@ -0,0 +1,7 @@
{
"extends": "./tsconfig.base",
"compilerOptions": {
"types": ["jest", "jest-matcher-specific-error"]
},
"include": ["src", "jest.config.ts"]
}

View file

@ -0,0 +1,6 @@
{
"extends": "./tsconfig",
"compilerOptions": {
"isolatedModules": false
}
}

View file

@ -0,0 +1,39 @@
{
"name": "@logto/shared",
"version": "0.1.0",
"main": "build/index.js",
"author": "Logto Team",
"license": "MPL-2.0",
"files": [
"lib"
],
"private": true,
"scripts": {
"preinstall": "npx only-allow pnpm",
"precommit": "lint-staged",
"build": "rm -rf build/ && tsc --p tsconfig.build.json",
"lint": "eslint --ext .ts src",
"lint:report": "pnpm lint -- --format json --output-file report.json",
"prepack": "pnpm build"
},
"engines": {
"node": ">=14.15.0"
},
"devDependencies": {
"@silverhand/eslint-config": "^0.10.2",
"@silverhand/essentials": "^1.1.6",
"@silverhand/ts-config": "^0.10.2",
"@types/node": "^16.3.1",
"eslint": "^8.10.0",
"lint-staged": "^11.1.1",
"prettier": "^2.3.2",
"typescript": "^4.6.2"
},
"eslintConfig": {
"extends": "@silverhand",
"rules": {
"@typescript-eslint/ban-types": "off"
}
},
"prettier": "@silverhand/eslint-config/.prettierrc"
}

View file

@ -0,0 +1,9 @@
import { existsSync, readFileSync } from 'fs';
export const getMarkdownContents = (filePath: string, fallbackContent: string): string => {
if (existsSync(filePath)) {
return readFileSync(filePath, 'utf8');
}
return fallbackContent;
};

View file

@ -0,0 +1,10 @@
{
"extends": "@silverhand/ts-config/tsconfig.base",
"compilerOptions": {
"outDir": "build",
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
}
}

View file

@ -0,0 +1,5 @@
{
"extends": "./tsconfig",
"include": ["src"],
"exclude": ["src/**/*.test.ts"]
}

View file

@ -0,0 +1,4 @@
{
"extends": "./tsconfig.base",
"include": ["src"]
}

135
pnpm-lock.yaml generated
View file

@ -57,6 +57,65 @@ importers:
ts-node: 10.4.0_e6a8a9b497f380f485f6d23f5cd591ca
typescript: 4.6.3
packages/connector-types:
specifiers:
'@jest/types': ^27.5.1
'@logto/phrases': ^0.1.0
'@logto/schemas': ^0.1.0
'@shopify/jest-koa-mocks': ^3.0.8
'@silverhand/eslint-config': ^0.10.2
'@silverhand/essentials': ^1.1.6
'@silverhand/ts-config': ^0.10.2
'@types/jest': ^27.4.1
eslint: ^8.10.0
got: ^11.8.2
jest: ^27.5.1
jest-matcher-specific-error: ^1.0.0
jose: ^3.14.3
lint-staged: ^11.1.1
prettier: ^2.3.2
ts-jest: ^27.1.1
typescript: ^4.6.2
dependencies:
'@logto/phrases': link:../phrases
'@logto/schemas': link:../schemas
got: 11.8.3
jose: 3.20.3
devDependencies:
'@jest/types': 27.5.1
'@shopify/jest-koa-mocks': 3.0.8
'@silverhand/eslint-config': 0.10.2_bbe1a6794670f389df81805f22999709
'@silverhand/essentials': 1.1.7
'@silverhand/ts-config': 0.10.2_typescript@4.6.3
'@types/jest': 27.4.1
eslint: 8.10.0
jest: 27.5.1
jest-matcher-specific-error: 1.0.0
lint-staged: 11.2.6
prettier: 2.5.1
ts-jest: 27.1.1_9985e1834e803358b7be1e6ce5ca0eea
typescript: 4.6.3
packages/connector-utils:
specifiers:
'@silverhand/eslint-config': ^0.10.2
'@silverhand/essentials': ^1.1.6
'@silverhand/ts-config': ^0.10.2
'@types/node': ^16.3.1
eslint: ^8.10.0
lint-staged: ^11.1.1
prettier: ^2.3.2
typescript: ^4.6.2
devDependencies:
'@silverhand/eslint-config': 0.10.2_bbe1a6794670f389df81805f22999709
'@silverhand/essentials': 1.1.7
'@silverhand/ts-config': 0.10.2_typescript@4.6.3
'@types/node': 16.11.12
eslint: 8.10.0
lint-staged: 11.2.6
prettier: 2.5.1
typescript: 4.6.3
packages/console:
specifiers:
'@logto/phrases': ^0.1.0
@ -6655,6 +6714,11 @@ packages:
string-width: 4.2.3
dev: true
/ansi-colors/4.1.1:
resolution: {integrity: sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA==}
engines: {node: '>=6'}
dev: true
/ansi-escapes/4.3.2:
resolution: {integrity: sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==}
engines: {node: '>=8'}
@ -7771,6 +7835,10 @@ packages:
resolution: {integrity: sha512-Uqbg+J445nc1TKn4FoDPS6ZZqAvEDnwrH42yo8B40JSOgSLxMZ/gt3h4nmCtPLQeXhjJJkqBx7SCY35WnIixaQ==}
dev: true
/colorette/1.4.0:
resolution: {integrity: sha512-Y2oEozpomLn7Q3HFP7dpww7AtMJplbM9lGZP6RDfHqmbeRjiwRg4n6VM6j4KLmRke85uWEI7JqF17f3pqdRA0g==}
dev: true
/colorette/2.0.16:
resolution: {integrity: sha512-hUewv7oMjCp+wkBv5Rm0v87eJhq4woh5rSR+42YSQJKecCqgIqNkZ6lAlQms/BwHPJA5NKMRlpxPRv0n8HQW6g==}
dev: true
@ -8520,6 +8588,19 @@ packages:
dependencies:
ms: 2.1.2
/debug/4.3.3_supports-color@8.1.1:
resolution: {integrity: sha512-/zxw5+vh1Tfv+4Qn7a5nsbcJKPaSvCDhojn6FEl9vupwK2VCSDtEiEtqr8DFtzYFOdz63LBkxec7DYuc2jon6Q==}
engines: {node: '>=6.0'}
peerDependencies:
supports-color: '*'
peerDependenciesMeta:
supports-color:
optional: true
dependencies:
ms: 2.1.2
supports-color: 8.1.1
dev: true
/debug/4.3.3_supports-color@9.2.2:
resolution: {integrity: sha512-/zxw5+vh1Tfv+4Qn7a5nsbcJKPaSvCDhojn6FEl9vupwK2VCSDtEiEtqr8DFtzYFOdz63LBkxec7DYuc2jon6Q==}
engines: {node: '>=6.0'}
@ -9006,6 +9087,13 @@ packages:
tapable: 2.2.1
dev: true
/enquirer/2.3.6:
resolution: {integrity: sha512-yjNnPr315/FjS4zIsUxYguYUPP2e1NK4d7E7ZOLiyYCcbFBiTMyID+2wvm2w6+pZ/odMA7cRkjhsPbltwBOrLg==}
engines: {node: '>=8.6'}
dependencies:
ansi-colors: 4.1.1
dev: true
/entities/1.1.2:
resolution: {integrity: sha512-f2LZMYl1Fzu7YSBKg+RoROelpOaNrcGmE9AZubeDfrCEia483oW4MI4VyFd5VNHIgQ/7qm1I0wUHK1eJnn2y2w==}
dev: true
@ -12661,6 +12749,26 @@ packages:
/lines-and-columns/1.2.4:
resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==}
/lint-staged/11.2.6:
resolution: {integrity: sha512-Vti55pUnpvPE0J9936lKl0ngVeTdSZpEdTNhASbkaWX7J5R9OEifo1INBGQuGW4zmy6OG+TcWPJ3m5yuy5Q8Tg==}
hasBin: true
dependencies:
cli-truncate: 2.1.0
colorette: 1.4.0
commander: 8.3.0
cosmiconfig: 7.0.1
debug: 4.3.3_supports-color@8.1.1
enquirer: 2.3.6
execa: 5.1.1
listr2: 3.14.0_enquirer@2.3.6
micromatch: 4.0.5
normalize-path: 3.0.0
please-upgrade-node: 3.2.0
string-argv: 0.3.1
stringify-object: 3.3.0
supports-color: 8.1.1
dev: true
/lint-staged/12.4.0:
resolution: {integrity: sha512-3X7MR0h9b7qf4iXf/1n7RlVAx+EzpAZXoCEMhVSpaBlgKDfH2ewf+QUm7BddFyq29v4dgPP+8+uYpWuSWx035A==}
engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
@ -12684,6 +12792,26 @@ packages:
- enquirer
dev: true
/listr2/3.14.0_enquirer@2.3.6:
resolution: {integrity: sha512-TyWI8G99GX9GjE54cJ+RrNMcIFBfwMPxc3XTFiAYGN4s10hWROGtOg7+O6u6LE3mNkyld7RSLE6nrKBvTfcs3g==}
engines: {node: '>=10.0.0'}
peerDependencies:
enquirer: '>= 2.3.0 < 3'
peerDependenciesMeta:
enquirer:
optional: true
dependencies:
cli-truncate: 2.1.0
colorette: 2.0.16
enquirer: 2.3.6
log-update: 4.0.0
p-map: 4.0.0
rfdc: 1.3.0
rxjs: 7.5.5
through: 2.3.8
wrap-ansi: 7.0.0
dev: true
/listr2/4.0.5:
resolution: {integrity: sha512-juGHV1doQdpNT3GSTs9IUN43QJb7KHdF9uqg7Vufs/tG9VTzpFphqF4pm/ICdAABGQxsyNn9CiYA3StkI6jpwA==}
engines: {node: '>=12'}
@ -14985,6 +15113,12 @@ packages:
find-up: 3.0.0
dev: true
/please-upgrade-node/3.2.0:
resolution: {integrity: sha512-gQR3WpIgNIKwBMVLkpMUeR3e1/E1y42bqDQZfql+kDeXd8COYfM8PQA4X6y7a8u9Ua9FHmsrrmirW2vHs45hWg==}
dependencies:
semver-compare: 1.0.0
dev: true
/pluralize/8.0.0:
resolution: {integrity: sha512-Nc3IT5yHzflTfbjgqWcCPpo7DaKy4FnpB0l/zCAW0Tc7jxAiuqSxHasntB3D7887LSrA93kDJ9IXovxJYxyLCA==}
engines: {node: '>=4'}
@ -17325,7 +17459,6 @@ packages:
/semver-compare/1.0.0:
resolution: {integrity: sha1-De4hahyUGrN+nvsXiPavxf9VN/w=}
dev: false
/semver-diff/3.1.1:
resolution: {integrity: sha512-GX0Ix/CJcHyB8c4ykpHGIAvLyOwOobtM/8d+TQkAd81/bEjgPHrfba41Vpesr7jX/t8Uh+R3EX9eAS5be+jQYg==}