Commit b34d0a3f authored by nanahira's avatar nanahira

first

parent e386456e
webpack.config.js
dist/*
build/*
*.js
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
stages:
- build
- deploy
variables:
GIT_DEPTH: "1"
build:
stage: build
tags:
- linux
script:
- npm ci
- npm run build
artifacts:
paths:
- dist/
deploy_npm:
stage: deploy
dependencies:
- build
tags:
- linux
script:
- apt update;apt -y install coreutils
- echo $NPMRC | base64 --decode > ~/.npmrc
- npm publish . --access public || true
only:
- master
/install-npm.sh
.git*
/data
/output
/config.yaml
.idea
.dockerignore
Dockerfile
/src
{
"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-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
This source diff could not be displayed because it is too large. You can view the blob instead.
{
"name": "@nanahira/s3-request-presigner",
"description": "Improved s3-request-presigner, with custom header support.",
"version": "1.0.0",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"lint": "eslint --fix .",
"build": "tsc",
"start": "node dist/index.js"
},
"repository": {
"type": "git",
"url": "https://code.mycard.moe/3rdeye/s3-request-presigner.git"
},
"author": "Nanahira <nanahira@momobako.com>",
"license": "MIT",
"keywords": [],
"bugs": {
"url": "https://code.mycard.moe/3rdeye/s3-request-presigner/issues"
},
"homepage": "https://code.mycard.moe/3rdeye/s3-request-presigner",
"dependencies": {
"@aws-sdk/middleware-sdk-s3": "^3.41.0",
"@aws-sdk/protocol-http": "^3.40.0",
"@aws-sdk/smithy-client": "^3.41.0",
"@aws-sdk/types": "^3.40.0",
"@aws-sdk/util-format-url": "^3.40.0"
},
"devDependencies": {
"@types/node": "^16.11.10",
"@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",
"prettier": "^2.5.0",
"typescript": "^4.5.2"
}
}
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",
"test/**/*.ts"
]
}
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