Commit 3cc4eb3f authored by nanahira's avatar nanahira

half

parent da9d3077
# compiled output
/dist
/node_modules
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
/data
/output
/config.yaml
.git*
Dockerfile
.dockerignore
webpack.config.js
dist/*
build/*
\ No newline at end of file
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
root: true,
env: {
node: true,
jest: true,
},
ignorePatterns: ['.eslintrc.js'],
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
};
# compiled output
/dist
/node_modules
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
/data
/output
/config.yaml
\ No newline at end of file
stages:
- build
- deploy
variables:
GIT_DEPTH: "1"
build:
stage: build
tags:
- linux
script:
- npm ci
- npm run build
artifacts:
paths:
- dist/
upload_to_minio:
stage: deploy
dependencies:
- build
tags:
- linux
script:
- aws s3 --endpoint=https://minio.mycard.moe:9000 sync --delete dist/full/ s3://nanahira/koishi-plugin/ygotournament
only:
- master
deploy_npm:
stage: deploy
dependencies:
- build
tags:
- linux
script:
- apt update;apt -y install coreutils
- echo $NPMRC | base64 --decode > ~/.npmrc
- npm publish . || true
only:
- master
/install-npm.sh
.git*
/data
/output
/config.yaml
.idea
.dockerignore
Dockerfile
/dist/full
\ No newline at end of file
{
"singleQuote": true,
"trailingComma": "all"
}
\ No newline at end of file
The MIT License (MIT)
Copyright (c) 2021 Nanahira
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
#!/bin/bash
npm install --save \
source-map-support
npm install --save-dev \
@types/node \
typescript \
'@typescript-eslint/eslint-plugin@^4.28.2' \
'@typescript-eslint/parser@^4.28.2 '\
'eslint@^7.30.0' \
'eslint-config-prettier@^8.3.0' \
'eslint-plugin-prettier@^3.4.0' \
prettier \
raw-loader \
ts-loader \
webpack \
webpack-cli \
koishi@next \
koishi-utils-schemagen
This diff is collapsed.
{
"name": "koishi-plugin-ygotournament",
"version": "1.0.0",
"description": "YGOPro 比赛使用的 Koishi 插件",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"lint": "eslint --fix .",
"build": "webpack && env PACK_AWS=1 webpack"
},
"repository": {
"type": "git",
"url": "https://code.mycard.moe/3rdeye/koishi-plugin-ygotournament.git"
},
"author": "Nanahira <nanahira@momobako.com>",
"license": "MIT",
"keywords": [
"Koishi.js",
"qqbot",
"cqhttp",
"onebot",
"ygo",
"yugioh",
"ygopro"
],
"bugs": {
"url": "https://code.mycard.moe/3rdeye/koishi-plugin-ygotournament/issues"
},
"homepage": "https://code.mycard.moe/3rdeye/koishi-plugin-ygotournament",
"dependencies": {
"@aws-sdk/client-s3": "^3.39.0",
"@aws-sdk/middleware-sdk-s3": "^3.39.0",
"@aws-sdk/protocol-http": "^3.38.0",
"@aws-sdk/smithy-client": "^3.38.0",
"@aws-sdk/types": "^3.38.0",
"@aws-sdk/util-format-url": "^3.38.0",
"class-transformer": "^0.4.0",
"koishi-utils-schemagen": "^1.1.9",
"source-map-support": "^0.5.20"
},
"peerDependencies": {
"koishi": "^4.0.0-alpha.12"
},
"devDependencies": {
"@types/node": "^16.11.6",
"@typescript-eslint/eslint-plugin": "^4.33.0",
"@typescript-eslint/parser": "^4.33.0",
"eslint": "^7.32.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^3.4.1",
"koishi": "^4.0.0-alpha.12",
"prettier": "^2.4.1",
"raw-loader": "^4.0.2",
"ts-loader": "^9.2.6",
"typescript": "^4.4.4",
"webpack": "^5.61.0",
"webpack-cli": "^4.9.1"
}
}
import 'source-map-support/register';
import { Credentials } from '@aws-sdk/types';
import {
DefineSchema,
SchemaConf,
schemaFromClass,
UseSchema,
} from 'koishi-utils-schemagen';
import path from 'path';
import { Context, Schema } from 'koishi';
import {
GetObjectCommand,
ListObjectsCommand,
S3,
S3Client,
S3ClientConfig,
} from '@aws-sdk/client-s3';
import { Tournament } from './def/challonge';
import { Type } from 'class-transformer';
import { SRVProRoomInfo } from './def/srvpro';
const credentialsSchema: Schema<Credentials> = Schema.object(
{
accessKeyId: Schema.string().required(),
secretAccessKey: Schema.string().required(),
},
true,
);
export const s3Schema: Schema<S3ClientConfig> = Schema.object(
{
region: Schema.string().default('none'),
endpoint: Schema.string(),
credentials: credentialsSchema,
},
true,
);
@SchemaConf({ desc: '发送卡组的置' })
export class DeckFetchConfig {
@DefineSchema({ desc: 'S3 配置', schema: s3Schema })
s3: S3ClientConfig;
@DefineSchema({ desc: '请求的 Host 字段' })
host: string;
@DefineSchema({ desc: '存储桶' })
bucket: string;
@DefineSchema({ desc: '卡组路径前缀', default: '' })
prefix: string;
@DefineSchema({ desc: 'URL 有效期', default: 600 })
urlAge: number;
S3Client(): S3Client {
const client = new S3Client({
region: 'none',
forcePathStyle: true,
...this.s3,
});
return client;
}
listCommand() {
return new ListObjectsCommand({
Bucket: this.bucket,
Prefix: this.prefix,
});
}
getObjectCommand(key: string) {
return new GetObjectCommand({
Bucket: this.bucket,
Key: key,
});
}
}
@SchemaConf({ desc: '比赛过程的设置' })
export class TournamentConfig {
@DefineSchema({
desc: '服务器 API 连接后台,不带任何路径和尾随斜杠',
})
endpoint: string;
@DefineSchema({ desc: '服务器后台用户名' })
username: string;
@DefineSchema({ desc: '服务器后台密码' })
password: string;
@DefineSchema({
desc: 'Challonge API Key',
})
challongeKey: string;
@DefineSchema({
desc: 'Challonge 比赛 ID',
})
challongeTournamentId: string;
@DefineSchema({
desc: 'Challonge 缓存时间',
default: 30000,
})
challongeCacheTTL: number;
async fetchRooms(ctx: Context) {
return ctx.http.get<Partial<SRVProRoomInfo>>(
`${this.endpoint}/api/getrooms`,
{
username: this.username,
pass: this.password,
},
);
}
}
export class YGOTournamentPluginConfig {
@DefineSchema()
tournament: TournamentConfig;
@DefineSchema()
deckFetch: DeckFetchConfig;
isTournamentEnabled() {
return !!this.tournament;
}
isDeckFetchEnabled() {
return !!this.deckFetch;
}
}
export interface YGOTournamentPluginConfigLike {
tournament?: Partial<TournamentConfig>;
deckFetch?: Partial<DeckFetchConfig>;
}
import { Type } from 'class-transformer';
export class Match {
attachment_count?: any;
created_at: string;
group_id?: any;
has_attachment: boolean;
id: number;
identifier: string;
location?: any;
loser_id?: any;
player1_id: number;
player1_is_prereq_match_loser: boolean;
player1_prereq_match_id?: any;
player1_votes?: any;
player2_id: number;
player2_is_prereq_match_loser: boolean;
player2_prereq_match_id?: any;
player2_votes?: any;
round: number;
scheduled_time?: any;
started_at: string;
state: string;
tournament_id: number;
underway_at?: any;
updated_at: string;
winner_id?: any;
prerequisite_match_ids_csv: string;
scores_csv: string;
}
export class MatchWrapper {
@Type(() => Match)
match: Match;
isClean() {
return (
this.match.state !== 'complete' &&
(this.match.scores_csv?.length && 0) < 3
);
}
getPlayerIds() {
return [this.match.player1_id, this.match.player2_id];
}
hasPlayer(id: number) {
return this.getPlayerIds().includes(id);
}
}
export class Participant {
active: boolean;
checked_in_at?: any;
created_at: string;
final_rank?: any;
group_id?: any;
icon?: any;
id: number;
invitation_id?: any;
invite_email?: any;
misc?: any;
name: string;
on_waiting_list: boolean;
seed: number;
tournament_id: number;
updated_at: string;
challonge_username?: any;
challonge_email_address_verified?: any;
removable: boolean;
participatable_or_invitation_attached: boolean;
confirm_remove: boolean;
invitation_pending: boolean;
display_name_with_invitation_email_address: string;
email_hash?: any;
username?: any;
attached_participatable_portrait_url?: any;
can_check_in: boolean;
checked_in: boolean;
reactivatable: boolean;
}
export class ParticipantWrapper {
@Type(() => Participant)
participant: Participant;
getNameMatching() {
const matching = this.participant.name.match(
/^([^\+ \uff0b]+)[\+ \uff0b](.+?)(\.ydk){0,2}$/,
);
if (!matching) {
return;
}
return { userId: matching[1], userName: matching[2] };
}
}
export class Tournament {
accept_attachments: boolean;
allow_participant_match_reporting: boolean;
anonymous_voting: boolean;
category?: any;
check_in_duration?: any;
completed_at?: any;
created_at: string;
created_by_api: boolean;
credit_capped: boolean;
description: string;
game_id: number;
group_stages_enabled: boolean;
hide_forum: boolean;
hide_seeds: boolean;
hold_third_place_match: boolean;
id: number;
max_predictions_per_user: number;
name: string;
notify_users_when_matches_open: boolean;
notify_users_when_the_tournament_ends: boolean;
open_signup: boolean;
participants_count: number;
prediction_method: number;
predictions_opened_at?: any;
private: boolean;
progress_meter: number;
pts_for_bye: string;
pts_for_game_tie: string;
pts_for_game_win: string;
pts_for_match_tie: string;
pts_for_match_win: string;
quick_advance: boolean;
ranked_by: string;
require_score_agreement: boolean;
rr_pts_for_game_tie: string;
rr_pts_for_game_win: string;
rr_pts_for_match_tie: string;
rr_pts_for_match_win: string;
sequential_pairings: boolean;
show_rounds: boolean;
signup_cap?: any;
start_at?: any;
started_at: string;
started_checking_in_at?: any;
state: string;
swiss_rounds: number;
teams: boolean;
tie_breaks: string[];
tournament_type: string;
updated_at: string;
url: string;
description_source: string;
subdomain?: any;
full_challonge_url: string;
live_image_url: string;
sign_up_url?: any;
review_before_finalizing: boolean;
accepting_predictions: boolean;
participants_locked: boolean;
game_name: string;
participants_swappable: boolean;
team_convertable: boolean;
group_stages_were_started: boolean;
@Type(() => ParticipantWrapper)
participants: ParticipantWrapper[];
@Type(() => MatchWrapper)
matches: MatchWrapper[];
}
export class TournamentWrapper {
@Type(() => Tournament)
tournament: Tournament;
getParticipantFromId(id: string) {
return this.tournament.participants.find(
(p) => p.getNameMatching()?.userId === id,
);
}
getCurrentMatchFromId(id: number) {
return this.tournament.matches.find(
(m) => m.match.state !== 'complete' && m.hasPlayer(id),
);
}
}
import { Type } from 'class-transformer';
export class Status {
score: number;
lp: number;
cards: number;
}
export class User {
id: string;
name: string;
ip?: string;
@Type(() => Status)
status?: Status;
pos: number;
isPlayer() {
return this.pos < 4;
}
getRealName() {
return this.name?.split('$')[0];
}
}
export class Room {
roomid: string;
roomname: string;
roommode: number;
needpass: string;
@Type(() => User)
users: User[];
istart: string;
includesUser(name: string) {
return this.users.find((u) => u.isPlayer() && u.getRealName() === name);
}
}
export class SRVProRoomInfo {
@Type(() => Room)
rooms: Room[];
searchForUser(name: string) {
return this.rooms.filter((r) => r.includesUser(name));
}
}
import 'source-map-support/register';
import { Context } from 'koishi';
import { YGOTournamentPlugin } from './plugin';
import { YGOTournamentPluginConfigLike } from './config';
export * from './config';
export * from './plugin';
export const name = 'ygotournament';
const plugin = new YGOTournamentPlugin();
export const schema = plugin.schema;
export function apply(ctx: Context, config: YGOTournamentPluginConfigLike) {
ctx.plugin(plugin, config);
}
import 'source-map-support/register';
import { Context, Schema } from 'koishi';
import {
YGOTournamentPluginConfig,
YGOTournamentPluginConfigLike,
} from './config';
import { schemaFromClass, schemaTransform } from 'koishi-utils-schemagen';
import { classToPlain, plainToClass } from 'class-transformer';
import { Tournament, TournamentWrapper } from './def/challonge';
import { S3Client } from '@aws-sdk/client-s3';
import { getSignedUrl } from './presign';
import { Room, SRVProRoomInfo } from './def/srvpro';
declare module 'koishi' {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace Cache {
interface Tables {
challongeData: any;
}
}
}
export class YGOTournamentPlugin {
private s3: S3Client;
private config: YGOTournamentPluginConfig;
private ctx: Context;
private async getChallongeCache() {
const data = this.ctx.cache.get(
'challongeData',
this.config.tournament.challongeTournamentId,
);
if (data) {
return plainToClass(TournamentWrapper, data);
}
}
private async deleteChallongeCache() {
return this.ctx.cache.del(
'challongeData',
this.config.tournament.challongeTournamentId,
);
}
private async setChallongeCache(data: TournamentWrapper) {
return this.ctx.cache.set(
'challongeData',
this.config.tournament.challongeTournamentId,
classToPlain(data),
);
}
private async fetchChallongeData() {
const cached = await this.getChallongeCache();
if (cached) {
return cached;
}
const plain = await this.ctx.http.get(
`https://api.challonge.com/v1/tournaments/${this.config.tournament.challongeTournamentId}.json`,
{
api_key: this.config.tournament.challongeKey,
include_participants: 1,
include_matches: 1,
},
);
const data = plainToClass(TournamentWrapper, plain);
await this.setChallongeCache(data);
return data;
}
private async onUserQuit(userId: string) {
const tournament = await this.fetchChallongeData();
const { matches } = tournament.tournament;
const participant = tournament.getParticipantFromId(userId);
if (!participant) {
return '未找到您的参赛信息。';
}
// const participantName = participant.getNameMatching().userName;
this.ctx
.logger('challonge')
.info(`Player ${participant.participant.name} requested for quit.`);
const currentMatch = tournament.getCurrentMatchFromId(
participant.participant.id,
);
if (currentMatch) {
const scores_csv =
participant.participant.id === currentMatch.match.player2_id
? '2--1'
: '-1-2';
this.ctx
.logger('challonge')
.info(
`Cleaning remaining match for player ${participant.participant.name}.`,
);
await this.ctx.http.put(
`https://api.challonge.com/v1/tournaments/${this.config.tournament.challongeTournamentId}/matches/${currentMatch.match.id}.json`,
{
api_key: this.config.tournament.challongeKey,
scores_csv,
winner_id: currentMatch
.getPlayerIds()
.find((id) => id !== participant.participant.id),
},
);
this.ctx
.logger('challonge')
.info(
`Cleaned remaining match for player ${participant.participant.name}.`,
);
await this.ctx.http.delete(
`https://api.challonge.com/v1/tournaments/${
this.config.tournament.challongeTournamentId
}/participants/${
participant.participant.id
}.json?api_key=${encodeURIComponent(
this.config.tournament.challongeKey,
)}`,
);
this.ctx
.logger('challonge')
.info(`Player ${participant.participant.name} quitted.`);
await this.deleteChallongeCache();
return '退赛成功。';
}
}
private async onUserDeclareLate(userId: string) {
const tournament = await this.fetchChallongeData();
const participant = tournament.getParticipantFromId(userId);
if (!participant) {
return '未找到您的参赛信息。';
}
const participantName = participant.getNameMatching().userName;
const currentMatch = tournament.getCurrentMatchFromId(
participant.participant.id,
);
if (!currentMatch) {
return '你没有当前轮次的比赛。';
}
if (!currentMatch.isClean()) {
return '你涉及的比赛似乎已经有结果了,请联系裁判处理。';
}
const rawRoomlist = await this.config.tournament.fetchRooms(this.ctx);
if (!rawRoomlist) {
return '获取房间列表失败,请与技术人员联系。';
}
const roomlist = plainToClass(SRVProRoomInfo, rawRoomlist);
const roomsWithPlayer = roomlist.searchForUser(participantName);
if (!roomsWithPlayer.length) {
return '请先进入房间并打勾确认。';
}
if (
roomsWithPlayer.some((r) => r.istart !== 'wait' || r.users.length > 1)
) {
return '对局已经开始,不能迟到杀。';
}
const scores_csv =
participant.participant.id === currentMatch.match.player1_id
? '2--1'
: '-1-2';
this.ctx
.logger('challonge')
.info(
`Player ${participant.participant.name} requested for a late declaration.`,
);
const result = await this.ctx.http.put(
`https://api.challonge.com/v1/tournaments/${this.config.tournament.challongeTournamentId}/matches/${currentMatch.match.id}.json`,
{
api_key: this.config.tournament.challongeKey,
scores_csv,
winner_id: participant.participant.id,
},
);
this.ctx
.logger('challonge')
.info(
`Result of late declaration for player ${
participant.participant.name
}: ${JSON.stringify(result)}`,
);
await this.deleteChallongeCache();
return '迟到杀成功。';
}
private initializeDeckFetch() {
if (!this.config.isDeckFetchEnabled()) {
return;
}
this.s3 = this.config.deckFetch.S3Client();
this.ctx
.command('tournament/deck', '获取自己的卡组')
.action(async ({ session }) => {
const userId = session.userId;
try {
const { Contents } = await this.s3.send(
this.config.deckFetch.listCommand(),
);
const deck = Contents.find(
(c) => c.Key.endsWith('.ydk') && c.Key.includes(userId),
);
if (!deck) {
return '未找到您的卡组。';
}
const url = await getSignedUrl(
this.s3,
this.config.deckFetch.getObjectCommand(deck.Key),
{
expiresIn: this.config.deckFetch.urlAge,
extraHeaders: this.config.deckFetch.host && {
host: this.config.deckFetch.host,
},
},
);
return `获取卡组成功。您可以在下列地址下载您的卡组:\n${url}`;
} catch (e) {
this.ctx
.logger('deckfetch')
.error(`Failed to fetch deck of ${userId}: ${e.toString()}`);
return '获取卡组出现了问题。请与技术人员联系。';
}
});
}
initializeTournament() {
if (!this.config.isTournamentEnabled()) {
return;
}
this.ctx.cache.table('challongeData', {
maxAge: this.config.tournament.challongeCacheTTL,
});
}
name = 'ygotournament-main';
schema: Schema<YGOTournamentPluginConfigLike> = schemaFromClass(
YGOTournamentPluginConfig,
);
apply(ctx: Context, config: YGOTournamentPluginConfigLike) {
this.ctx = ctx;
this.config = schemaTransform(YGOTournamentPluginConfig, config);
this.ctx.command('tournament', 'YGOPro 比赛相关命令');
this.initializeTournament();
this.initializeDeckFetch();
}
}
export const UNSIGNED_PAYLOAD = 'UNSIGNED-PAYLOAD';
export const SHA256_HEADER = 'X-Amz-Content-Sha256';
export const ALGORITHM_QUERY_PARAM = 'X-Amz-Algorithm';
export const CREDENTIAL_QUERY_PARAM = 'X-Amz-Credential';
export const AMZ_DATE_QUERY_PARAM = 'X-Amz-Date';
export const SIGNED_HEADERS_QUERY_PARAM = 'X-Amz-SignedHeaders';
export const EXPIRES_QUERY_PARAM = 'X-Amz-Expires';
export const HOST_HEADER = 'host';
export const ALGORITHM_IDENTIFIER = 'AWS4-HMAC-SHA256';
import { HttpRequest } from '@aws-sdk/protocol-http';
import { Client, Command } from '@aws-sdk/smithy-client';
import {
BuildMiddleware,
MetadataBearer,
RequestPresigningArguments,
} from '@aws-sdk/types';
import { formatUrl } from '@aws-sdk/util-format-url';
import { S3RequestPresigner } from './presigner';
export interface RequestPresigningArgumentsWithHeaders
extends RequestPresigningArguments {
extraHeaders?: Record<string, string>;
}
export const getSignedUrl = async <
InputTypesUnion extends Record<string, any>,
InputType extends InputTypesUnion,
OutputType extends MetadataBearer = MetadataBearer
>(
client: Client<any, InputTypesUnion, MetadataBearer, any>,
command: Command<InputType, OutputType, any, InputTypesUnion, MetadataBearer>,
options: RequestPresigningArgumentsWithHeaders = {},
): Promise<string> => {
const s3Presigner = new S3RequestPresigner({ ...client.config });
const presignInterceptMiddleware: BuildMiddleware<
InputTypesUnion,
MetadataBearer
> = (next, context) => async (args) => {
const { request } = args;
if (!HttpRequest.isInstance(request)) {
throw new Error('Request to be presigned is not an valid HTTP request.');
}
// Retry information headers are not meaningful in presigned URLs
delete request.headers['amz-sdk-invocation-id'];
delete request.headers['amz-sdk-request'];
// User agent header would leak sensitive information
delete request.headers['x-amz-user-agent'];
const presigned = await s3Presigner.presign(request, {
...options,
signingRegion: options.signingRegion ?? context['signing_region'],
signingService: options.signingService ?? context['signing_service'],
});
return {
// Intercept the middleware stack by returning fake response
response: {},
output: {
$metadata: { httpStatusCode: 200 },
presigned,
},
} as any;
};
const middlewareName = 'presignInterceptMiddleware';
client.middlewareStack.addRelativeTo(presignInterceptMiddleware, {
name: middlewareName,
relation: 'before',
toMiddleware: 'awsAuthMiddleware',
override: true,
});
let presigned: HttpRequest;
try {
const output = await client.send(command);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore the output is faked, so it's not actually OutputType
presigned = output.presigned;
} finally {
client.middlewareStack.remove(middlewareName);
}
return formatUrl(presigned);
};
export * from './getSignedUrl';
export * from './presigner';
import { S3SignatureV4, S3SignerV4Init } from '@aws-sdk/middleware-sdk-s3';
import { RequestPresigner } from '@aws-sdk/types';
import { HttpRequest as IHttpRequest } from '@aws-sdk/types';
import { SHA256_HEADER, UNSIGNED_PAYLOAD } from './constants';
import { RequestPresigningArgumentsWithHeaders } from './getSignedUrl';
type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
export type S3RequestPresignerOptions = PartialBy<
S3SignerV4Init,
'service' | 'uriEscapePath'
> & {
signingName?: string;
};
export class S3RequestPresigner implements RequestPresigner {
private readonly signer: S3SignatureV4;
constructor(options: S3RequestPresignerOptions) {
const resolvedOptions = {
// Allow `signingName` because we want to support usecase of supply client's resolved config
// directly. Where service equals signingName.
service: options.signingName || options.service || 's3',
uriEscapePath: options.uriEscapePath || false,
applyChecksum: options.applyChecksum || false,
...options,
};
this.signer = new S3SignatureV4(resolvedOptions);
}
public async presign(
requestToSign: IHttpRequest,
{
unsignableHeaders = new Set(),
unhoistableHeaders = new Set(),
...options
}: RequestPresigningArgumentsWithHeaders = {},
): Promise<IHttpRequest> {
unsignableHeaders.add('content-type');
// S3 requires SSE headers to be signed in headers instead of query
// See: https://github.com/aws/aws-sdk-js-v3/issues/1576
Object.keys(requestToSign.headers)
.map((header) => header.toLowerCase())
.filter((header) => header.startsWith('x-amz-server-side-encryption'))
.forEach((header) => {
unhoistableHeaders.add(header);
});
requestToSign.headers[SHA256_HEADER] = UNSIGNED_PAYLOAD;
if (!requestToSign.headers['host']) {
requestToSign.headers.host = requestToSign.hostname;
if (requestToSign.port) {
requestToSign.headers.host = `${requestToSign.headers.host}:${requestToSign.port}`;
}
}
requestToSign.headers = {
...requestToSign.headers,
...(options.extraHeaders || {}),
};
return this.signer.presign(requestToSign, {
expiresIn: 900,
unsignableHeaders,
unhoistableHeaders,
...options,
});
}
}
{
"compilerOptions": {
"outDir": "dist",
"module": "commonjs",
"target": "es2021",
"esModuleInterop": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"declaration": true,
"sourceMap": true
},
"compileOnSave": true,
"allowJs": true,
"include": [
"*.ts",
"src/**/*.ts"
]
}
const path = require('path');
const packAll = !!process.env.PACK_ALL;
module.exports = {
entry: './src/index.ts',
mode: 'production',
target: 'node',
devtool: 'source-map',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
{ test: /\.mustache$/, use: 'raw-loader' },
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
output: {
filename: 'index.js',
library: {
type: 'commonjs',
},
path: path.resolve(__dirname, packAll ? 'dist/full' : 'dist'),
},
externals: {
koishi: 'koishi',
...(packAll
? {}
: {
'@aws-sdk/client-s3': '@aws-sdk/client-s3',
'@aws-sdk/middleware-sdk-s3': '@aws-sdk/middleware-sdk-s3',
'@aws-sdk/protocol-http': '@aws-sdk/protocol-http',
'@aws-sdk/smithy-client': '@aws-sdk/smithy-client',
'@aws-sdk/util-format-url': '@aws-sdk/util-format-url',
'koishi-utils-schemagen': 'koishi-utils-schemagen',
'class-transformer': 'class-transformer',
}),
},
};
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment