This commit is contained in:
2023-09-23 12:46:52 +00:00
parent 93686c4912
commit 9c9d9e9545
47 changed files with 84 additions and 657 deletions
-208
View File
@@ -1,208 +0,0 @@
import 'dotenv/config';
import { AES_GCM_Decrypt, AES_GCM_Encrypt } from "./util/aes.js";
import { webcrypto } from "crypto";
import { Buffer } from "buffer";
import { sha512 } from "./util/sha2.js";
import { BSON } from "bson";
/**
* Preshared Token Secret을 이용한 AES256-GCM 토큰
* key, iv = SHA512(presharedSecret + nonce) 으로 생성
*/
export type SecureEncryptedToken = {
nonce: string; // [key, iv] = SHA512(presharedSecret + nonce)
encrypted: 1;
type: string; // aad[0]
validUntil: string; // aad[1]
payload: string; //BASE64(AES(BSON(aad),BSON(payload)))
}
export type SecurePlaintextToken = {
nonce: string; // [key, iv] = SHA512(presharedSecret + nonce)
encrypted: 0;
type: string; // aad[0]
validUntil: string; // aad[1]
payload: string; // JSON => aad[2]
tag: string; //BASE64(AES(BSON(aad),null)))
}
export type SecureToken = SecureEncryptedToken | SecurePlaintextToken;
const staticPresharedTokenSecret: string | undefined = process.env.PRESHARED_TOKEN_SECRET;
export async function generateSecureEncryptedToken<T extends object>(validUntil: Date, type: string, payload: T, presharedTokenSecret?: string): Promise<SecureEncryptedToken> {
if (!presharedTokenSecret) {
if (!staticPresharedTokenSecret) {
throw new Error("PRESHARED_TOKEN_SECRET is not set");
}
presharedTokenSecret = staticPresharedTokenSecret;
}
const secretLength = Buffer.byteLength(presharedTokenSecret, 'utf8');
const secretBuffer = Buffer.alloc(secretLength + 16);
secretBuffer.write(presharedTokenSecret, 0, secretLength, 'utf8');
//secretBuffer에서 Buffer를 바로 준비해도 되지만, 혹시모를 안전상의 이유로 별도로 할당하고 복사
const nonce = Buffer.from(webcrypto.getRandomValues(new Uint8Array(16)));
secretBuffer.set(nonce, secretLength);
const keyBuffer = Buffer.from(await sha512(secretBuffer));
const key = new Uint8Array(keyBuffer.buffer, 0, 32);
const iv = new Uint8Array(keyBuffer.buffer, 32, 12);
const validUntilText = validUntil.toISOString();
const aad = [type, validUntilText];
const aadRaw = BSON.serialize(aad);
const payloadRaw = BSON.serialize(payload);
const ciphertext = Buffer.from(await AES_GCM_Encrypt(key, iv, payloadRaw, aadRaw));
return {
nonce: nonce.toString('base64'),
encrypted: 1,
type,
validUntil: validUntilText,
payload: ciphertext.toString('base64'),
}
}
export async function parseSecureEncryptedToken<T extends object>(secureToken: SecureEncryptedToken, presharedTokenSecret?: string): Promise<T> {
const now = new Date();
const validUntil = new Date(secureToken.validUntil);
if (now > validUntil) {
throw new Error("token expired");
}
if(!secureToken.encrypted) {
throw new Error("token is not encrypted");
}
if (!presharedTokenSecret) {
if (!staticPresharedTokenSecret) {
throw new Error("PRESHARED_TOKEN_SECRET is not set");
}
presharedTokenSecret = staticPresharedTokenSecret;
}
const secretLength = Buffer.byteLength(presharedTokenSecret, 'utf8');
const secretBuffer = Buffer.alloc(secretLength + 16);
secretBuffer.write(presharedTokenSecret, 0, secretLength, 'utf8');
const nonce = Buffer.from(secureToken.nonce, 'base64');
secretBuffer.set(nonce, secretLength);
const keyBuffer = Buffer.from(await sha512(secretBuffer));
const key = new Uint8Array(keyBuffer.buffer, 0, 32);
const iv = new Uint8Array(keyBuffer.buffer, 32, 12);
const aad = [secureToken.type, secureToken.validUntil];
const aadRaw = BSON.serialize(aad);
const payloadCiphertext = Buffer.from(secureToken.payload, 'base64');
const payloadRaw = new Uint8Array(await AES_GCM_Decrypt(key, iv, payloadCiphertext, aadRaw));
const payload = BSON.deserialize(payloadRaw);
return payload as T;
}
export async function generateSecurePlaintextToken<T extends object>(validUntil: Date, type: string, payload: T, presharedTokenSecret?: string): Promise<SecurePlaintextToken> {
if (!presharedTokenSecret) {
if (!staticPresharedTokenSecret) {
throw new Error("PRESHARED_TOKEN_SECRET is not set");
}
presharedTokenSecret = staticPresharedTokenSecret;
}
const secretLength = Buffer.byteLength(presharedTokenSecret, 'utf8');
const secretBuffer = Buffer.alloc(secretLength + 16);
secretBuffer.write(presharedTokenSecret, 0, secretLength, 'utf8');
//secretBuffer에서 Buffer를 바로 준비해도 되지만, 혹시모를 안전상의 이유로 별도로 할당하고 복사
const nonce = Buffer.from(webcrypto.getRandomValues(new Uint8Array(16)));
secretBuffer.set(nonce, secretLength);
const keyBuffer = Buffer.from(await sha512(secretBuffer));
const key = new Uint8Array(keyBuffer.buffer, 0, 32);
const iv = new Uint8Array(keyBuffer.buffer, 32, 12);
const validUntilText = validUntil.toISOString();
const jsonPayload = JSON.stringify(payload);
const aad = [type, validUntilText, jsonPayload];
const aadRaw = BSON.serialize(aad);
const dummyPayload = new ArrayBuffer(0);
const tag = Buffer.from(await AES_GCM_Encrypt(key, iv, dummyPayload, aadRaw));
return {
nonce: nonce.toString('base64'),
encrypted: 0,
type,
validUntil: validUntilText,
payload: jsonPayload,
tag: tag.toString('base64'),
}
}
export async function parseSecurePlaintextToken<T extends object>(secureToken: SecurePlaintextToken, presharedTokenSecret?: string): Promise<T> {
const now = new Date();
const validUntil = new Date(secureToken.validUntil);
if (now > validUntil) {
throw new Error("token expired");
}
if (!presharedTokenSecret) {
if (!staticPresharedTokenSecret) {
throw new Error("PRESHARED_TOKEN_SECRET is not set");
}
presharedTokenSecret = staticPresharedTokenSecret;
}
if (secureToken.encrypted) {
throw new Error("token is encrypted");
}
const secretLength = Buffer.byteLength(presharedTokenSecret, 'utf8');
const secretBuffer = Buffer.alloc(secretLength + 16);
secretBuffer.write(presharedTokenSecret, 0, secretLength, 'utf8');
const nonce = Buffer.from(secureToken.nonce, 'base64');
secretBuffer.set(nonce, secretLength);
const keyBuffer = Buffer.from(await sha512(secretBuffer));
const key = new Uint8Array(keyBuffer.buffer, 0, 32);
const iv = new Uint8Array(keyBuffer.buffer, 32, 12);
const aad = [secureToken.type, secureToken.validUntil, secureToken.payload];
const aadRaw = BSON.serialize(aad);
const tag = Buffer.from(secureToken.tag, 'base64');
await AES_GCM_Decrypt(key, iv, tag, aadRaw);
return JSON.parse(secureToken.payload);
}
export async function generateSecureToken<T extends object>(encrypted: boolean, validUntil: Date, type: string, payload: T, presharedTokenSecret?: string): Promise<SecureToken> {
if (encrypted) {
return await generateSecureEncryptedToken(validUntil, type, payload, presharedTokenSecret);
} else {
return await generateSecurePlaintextToken(validUntil, type, payload, presharedTokenSecret);
}
}
export async function parseSecureToken<T extends object>(secureToken: SecureToken, presharedTokenSecret?: string): Promise<T> {
if (secureToken.encrypted) {
return await parseSecureEncryptedToken(secureToken, presharedTokenSecret);
} else {
return await parseSecurePlaintextToken(secureToken, presharedTokenSecret);
}
}
@@ -1,25 +0,0 @@
import { GET } from "../defs.js";
import type { structure } from "../../apiStructure/sammoGatewayAPI.js";
import type { ExtractError, ExtractQuery, ExtractResponse } from "../../apiStructure/defs.js";
import { StartSession } from "../../ProcDecorator/StartSession.js";
import { declProcDecorators } from "../../ProcDecorator/base.js";
import { ReqLogin } from "../../ProcDecorator/ReqLogin.js";
type BaseAPI = typeof structure.GetGameLoginToken;
type RType = ExtractResponse<BaseAPI>;
type EType = ExtractError<BaseAPI>;
type QType = ExtractQuery<BaseAPI>;
export const GameLoginTokenSessionKey = "GameLoginToken";
export const GetGameLoginToken = GET<RType, EType, QType>(undefined)(declProcDecorators(
StartSession,
ReqLogin,
))(
async (query, ctx) => {
return {
result: false,
reason: 'NotYetImplemented',
};
}
);
@@ -1,21 +0,0 @@
import { GET } from "../../defs.js";
import type { structure } from "../../../apiStructure/sammoGatewayAPI.js";
import type { ExtractError, ExtractQuery, ExtractResponse } from "../../../apiStructure/defs.js";
import { declProcDecorators } from "../../../ProcDecorator/base.js";
import { ReqLogin } from "../../../ProcDecorator/ReqLogin.js";
import { StartSession } from "../../../ProcDecorator/StartSession.js";
type BaseAPI = typeof structure.Login.ReqNonce;
type RType = ExtractResponse<BaseAPI>;
type EType = ExtractError<BaseAPI>;
type QType = ExtractQuery<BaseAPI>;
const argValidator = undefined;
export const ReqNonce = GET<RType, EType, QType>(argValidator)(declProcDecorators(
StartSession,
ReqLogin,
))(
(query, ctx) => {
throw new Error("Method not implemented.");
}
);
-64
View File
@@ -1,64 +0,0 @@
import { POST } from "../../defs.js";
import type { structure } from "../../../apiStructure/sammoGatewayAPI.js";
import type { ExtractError, ExtractQuery, ExtractResponse } from "../../../apiStructure/defs.js";
import { StartSession } from "../../../ProcDecorator/StartSession.js";
import { delay } from "../../../util/delay.js";
import { declProcDecorators } from "../../../ProcDecorator/base.js";
import { z } from "zod";
import { type LoginCtx, loginCtxSessionKey } from "../../../ProcDecorator/ReqLogin.js";
type BaseAPI = typeof structure.Login.LoginByID;
type RType = ExtractResponse<BaseAPI>;
type EType = ExtractError<BaseAPI>;
type QType = ExtractQuery<BaseAPI>;
const LoginByIDReq = z.object({
id: z.string(),
password: z.string(),
}) satisfies z.ZodType<QType>
export const LoginByID = POST<RType, EType, QType>(LoginByIDReq)(declProcDecorators(
StartSession,
))(
async (query, ctx, req, res) => {
const id = query.id;
const password = query.password;
//TODO: DB에서 뭔가 가져와야 함
await delay(1);
if (Math.random() < 0.3) {
return {
result: false,
reason: "로그인 실패",
reqOTP: false,
}
}
if (Math.random() < 0.5) {
return {
result: false,
reason: "OTP 인증 필요",
reqOTP: true,
}
}
const userID = 1;
const userName = "test";
const userLevel = 1;
const nextToken: [number, string] = [1, "1234567890"];
const loginCtx: LoginCtx = {
userID,
userName,
userLevel,
allowServerAction: new Set(),
loginDate: new Date(),
}
ctx.session.setItem(loginCtxSessionKey, loginCtx);
return {
result: true,
nextToken,
}
});
@@ -1,51 +0,0 @@
import { POST } from "../../defs.js";
import type { structure } from "../../../apiStructure/sammoGatewayAPI.js";
import type { ExtractError, ExtractQuery, ExtractResponse } from "../../../apiStructure/defs.js";
import { StartSession } from "../../../ProcDecorator/StartSession.js";
import { delay } from "../../../util/delay.js";
import { declProcDecorators } from "../../../ProcDecorator/base.js";
import { type LoginCtx, loginCtxSessionKey } from "../../../ProcDecorator/ReqLogin.js";
import { z } from "zod";
type BaseAPI = typeof structure.Login.LoginByToken;
type RType = ExtractResponse<BaseAPI>;
type EType = ExtractError<BaseAPI>;
type QType = ExtractQuery<BaseAPI>;
const LoginByTokenReq = z.object({
token_id: z.number(),
hashedToken: z.string(),
}) satisfies z.ZodType<QType>
export const LoginByToken = POST<RType, EType, QType>(LoginByTokenReq)(declProcDecorators(
StartSession,
))
(async (query, ctx) => {
query.hashedToken;
ctx.session.clear();
await delay(1);
//무언가 로그인
//TODO: DB는 어디서 들고옴?
const userID = 1;
const userName = "test";
const userLevel = 1;
const nextToken: [number, string] = [1, "1234567890"];
const loginCtx: LoginCtx = {
userID,
userName,
userLevel,
allowServerAction: new Set(),
loginDate: new Date(),
}
ctx.session.setItem(loginCtxSessionKey, loginCtx);
//throw new Error("Method not implemented.");
return {
result: true,
nextToken,
}
});
-33
View File
@@ -1,33 +0,0 @@
import { GET } from "../../defs.js";
import type { structure } from "../../../apiStructure/sammoGatewayAPI.js";
import type { ExtractError, ExtractQuery, ExtractResponse } from "../../../apiStructure/defs.js";
import { StartSession } from "../../../ProcDecorator/StartSession.js";
import { declProcDecorators } from "../../../ProcDecorator/base.js";
type BaseAPI = typeof structure.Login.ReqNonce;
type RType = ExtractResponse<BaseAPI>;
type EType = ExtractError<BaseAPI>;
type QType = ExtractQuery<BaseAPI>;
export const ReqNonceSessionKey = 'loginNonce';
export const ReqNonce = GET<RType, EType, QType>(undefined)(declProcDecorators(
StartSession,
))(
async (query, ctx) => {
const nonce = ctx.session.getItem<string>(ReqNonceSessionKey);
if (nonce !== undefined) {
return {
loginNonce: nonce,
result: true,
}
}
const newNonce = "1234567890";
ctx.session.setItem(ReqNonceSessionKey, newNonce);
return {
loginNonce: newNonce,
result: true,
}
}
)
-13
View File
@@ -1,13 +0,0 @@
import type { structure } from "../../../apiStructure/sammoGatewayAPI.js";
import type { APINamespaceType } from "../../defs.js";
import { LoginByID } from "./LoginByID.js";
import { LoginByToken } from "./LoginByToken.js";
import { ReqNonce } from "./ReqNonce.js";
import { test } from "./test.js";
export const Login = {
LoginByID,
LoginByToken,
ReqNonce,
test,
} satisfies APINamespaceType<typeof structure.Login>;
-15
View File
@@ -1,15 +0,0 @@
import { GET } from "../../defs.js";
import type { structure } from "../../../apiStructure/sammoGatewayAPI.js";
import type { ExtractError, ExtractQuery, ExtractResponse } from "../../../apiStructure/defs.js";
import { EmptyProcDecorator } from "../../../ProcDecorator/base.js";
type BaseAPI = typeof structure.Login.test;
type RType = ExtractResponse<BaseAPI>;
type EType = ExtractError<BaseAPI>;
type QType = ExtractQuery<BaseAPI>;
export const test = GET<RType, EType, QType>(undefined)(EmptyProcDecorator)(
() => {
throw new Error("Method not implemented.");
}
);
-9
View File
@@ -1,9 +0,0 @@
import type { structure } from "../apiStructure/sammoGatewayAPI.js";
import type { APINamespaceType } from "./defs.js";
import { GetGameLoginToken } from "./GatewayAPI/GetGameLoginToken.js";
import { Login } from "./GatewayAPI/Login/index.js";
export const sammoGatewayAPI = {
Login,
GetGameLoginToken
} satisfies APINamespaceType<typeof structure>;
-52
View File
@@ -1,52 +0,0 @@
import { type DefAPINamespace, GET, POST } from "./defs.js";
export type LoginResponse = {
result: true,
nextToken: [number, string] | undefined,
}
export type LoginFailed = {
result: false,
reqOTP: boolean,
reason: string,
}
export type AutoLoginNonceResponse = {
result: true,
loginNonce: string,
};
export type AutoLoginResponse = {
result: true,
nextToken: [number, string] | undefined,
}
export type AutoLoginFailed = {
result: false,
silent: boolean,
reason: string,
}
/** @internal */
export const structure = {
Login: {
LoginByID: POST<{
id: string,
password: string,
}, LoginResponse, LoginFailed>(),
LoginByToken: POST<{
hashedToken: string,
token_id: number,
}, AutoLoginResponse, AutoLoginFailed>(),
ReqNonce: GET<AutoLoginNonceResponse, AutoLoginFailed>(),
test: GET<{result: true, hello:'world'}>(),
},
GetGameLoginToken: GET<{
result: true,
gameLoginToken: string,
userID: number,
}>(),
} satisfies DefAPINamespace;
-26
View File
@@ -1,26 +0,0 @@
export function APIPathGen<T, V>(
obj: T,
callback: (path: string[], tail: V, pathParam?: Record<string, string | number>) => unknown,
pathParam?: Record<string, string | number>
): T;
export function StrVar<PathType extends string>(paramKey: string): <NextCall>(next: NextCall) => {
[v in PathType]: NextCall
};
export function NumVar<NextCall>(paramKey: string, next: NextCall): {
[v: number]: NextCall
};
/*
const apiPath = {
SomePath: someFunc,
User: StrVar<'a'|'b'>('name')({
Update: someFunc,
Delete: someFunc,
}),
NationInfo: NumVar('id', {
show: someFunc
})
}
*/
-68
View File
@@ -1,68 +0,0 @@
export function APIPathGen(obj, callback, path, pathParams) {
return new Proxy(obj, {
get(target, key) {
let nextPath;
if (path === undefined) {
nextPath = [key.toString()];
}
else {
nextPath = [...path, key.toString()];
}
if (pathParams !== undefined) {
pathParams = { ...pathParams };
}
const varType = target.__nextVarType;
let varKey = target.__nextVarKey;
let next;
if (varType !== undefined && varKey !== undefined) {
if(varType == 'number'){
if(key != Number(key)){
throw `${key} is not ${varType}`;
}
key = Number(key);
}
else if ((typeof key) !== varType) {
throw `${key} is not ${varType}, but ${typeof key}`;
}
if(pathParams === undefined){
pathParams = {}
}
pathParams[varKey] = key;
nextPath.pop();
next = target.next;
}
else if (key in target) {
next = target[key];
}
else {
throw `${nextPath} is not exists`;
}
if (typeof (next) === 'function') {
return callback(nextPath, next, pathParams);
}
return APIPathGen(next, callback, nextPath, pathParams);
}
})
}
//generic 인자로 '자동'을 주려면 생략해야하므로 2단 호출
export function StrVar(key) {
return (next) => {
return {
__nextVarType: 'string',
__nextVarKey: key,
next
}
}
}
export function NumVar(key, next) {
return {
__nextVarType: 'number',
__nextVarKey: key,
next
}
}
-2
View File
@@ -1,2 +0,0 @@
export type Bytes = ArrayBuffer | DataView | Uint8Array;
export type BytesLike = Bytes | string;
-264
View File
@@ -1,264 +0,0 @@
import type { RNG } from "./RNG.js";
import { sha512 } from './sha2.js';
import { convertBytesLikeToUint8Array } from "./convertBytesLikeToUint8Array.js";
import type { BytesLike } from "./BytesLike.js";
import { delay } from "./delay.js";
const maxRngSupportBit = 53;
const maxInt = 0x1f_ffff_ffff_ffff; // NOTE: b 0, 10000110011, 11...11
const maxIntMore1 = 0x20_0000_0000_0000n; //NOTE: b 0, 10000110100, 00...00
const maxIntMore1f = Number(maxIntMore1);
export const bufferByteSize = 512 / 8; //SHA512
const intBitMapMask = new Map([
[0x1n, 1],
[0x3n, 2],
[0x7n, 3],
[0xfn, 4],
[0x1fn, 5],
[0x3fn, 6],
[0x7fn, 7],
[0xffn, 8],
[0x1ffn, 9],
[0x3ffn, 10],
[0x7ffn, 11],
[0xfffn, 12],
[0x1fffn, 13],
[0x3fffn, 14],
[0x7fffn, 15],
[0xffffn, 16],
[0x1ffffn, 17],
[0x3ffffn, 18],
[0x7ffffn, 19],
[0xfffffn, 20],
[0x1fffffn, 21],
[0x3fffffn, 22],
[0x7fffffn, 23],
[0xffffffn, 24],
[0x1ffffffn, 25],
[0x3ffffffn, 26],
[0x7ffffffn, 27],
[0xfffffffn, 28],
[0x1fffffffn, 29],
[0x3fffffffn, 30],
[0x7fffffffn, 31],
[0xffffffffn, 32],
[0x1ffffffffn, 33],
[0x3ffffffffn, 34],
[0x7ffffffffn, 35],
[0xfffffffffn, 36],
[0x1fffffffffn, 37],
[0x3fffffffffn, 38],
[0x7fffffffffn, 39],
[0xffffffffffn, 40],
[0x1ffffffffffn, 41],
[0x3ffffffffffn, 42],
[0x7ffffffffffn, 43],
[0xfffffffffffn, 44],
[0x1fffffffffffn, 45],
[0x3fffffffffffn, 46],
[0x7fffffffffffn, 47],
[0xffffffffffffn, 48],
[0x1ffffffffffffn, 49],
[0x3ffffffffffffn, 50],
[0x7ffffffffffffn, 51],
[0xfffffffffffffn, 52],
[0x1fffffffffffffn, 53],
]);
function calcBitMask(n: bigint): bigint {
n |= n >> 1n;
n |= n >> 2n;
n |= n >> 4n;
n |= n >> 8n;
n |= n >> 16n;
n |= n >> 32n;
return n;
}
export class LiteHashDRBG implements RNG {
protected buffer!: ArrayBuffer;
protected bufferIdx!: number;
protected hq: DataView;
protected hqIdxPos: number;
protected ready: Promise<void>;
public constructor(protected seed: BytesLike, protected stateIdx = 0, bufferIdx = 0) {
if (bufferIdx < 0) {
throw new Error(`bufferIdx ${bufferIdx} < 0`);
}
if (bufferIdx >= bufferByteSize) {
throw new Error(`bufferidx ${bufferIdx} >= ${bufferByteSize}`);
}
if (stateIdx < 0) {
throw new Error(`stateIdx ${stateIdx} < 0`);
}
const seedU8 = convertBytesLikeToUint8Array(seed);
const hqBuffer = new ArrayBuffer(seedU8.byteLength + 4);
const hqU8 = new Uint8Array(hqBuffer);
hqU8.set(seedU8, 0);
this.hq = new DataView(hqBuffer);
this.hqIdxPos = seedU8.byteLength;
this.ready = this.genNextBlock();
this.bufferIdx = bufferIdx;
}
protected async genNextBlock(): Promise<void> {
this.bufferIdx = 0;
this.hq.setUint32(this.hqIdxPos, this.stateIdx, true);
this.stateIdx += 1;
const digest = await sha512(this.hq.buffer);
this.buffer = digest;
}
public getMaxInt(): number {
return maxInt;
}
public async nextBytes(bytes: number, baseBytes?: number): Promise<Uint8Array> {
bytes |= 0;
if (bytes <= 0) {
throw new Error(`${bytes} <= 0`);
}
const ticket = this.ready;
let waiter: Promise<Uint8Array | undefined> = Promise.resolve(undefined);
let nextBlockWait: (() => void) | null = (() => { throw 'something wrong'; });
this.ready = new Promise((resolve, reject) => {
waiter = (async () => {
await ticket;
nextBlockWait = resolve;
if (this.bufferIdx + bytes <= bufferByteSize) {
if (baseBytes === undefined || bytes >= baseBytes) {
const result = this.buffer.slice(this.bufferIdx, this.bufferIdx + bytes);
this.bufferIdx += bytes;
if (this.bufferIdx === bufferByteSize) {
nextBlockWait = null;
this.genNextBlock().then(resolve, reject);
}
return new Uint8Array(result);
}
const resultBuffer = new ArrayBuffer(Math.max(bytes, baseBytes ?? 0));
const result = new Uint8Array(resultBuffer);
result.set(new Uint8Array(this.buffer, this.bufferIdx, bytes));
this.bufferIdx += bytes;
if (this.bufferIdx === bufferByteSize) {
nextBlockWait = null;
this.genNextBlock().then(resolve, reject);
}
return result;
}
const resultBuffer = new ArrayBuffer(baseBytes ? Math.max(bytes, baseBytes) : bytes);
const result = new Uint8Array(resultBuffer);
result.set(new Uint8Array(this.buffer, this.bufferIdx));
let offset = bufferByteSize - this.bufferIdx;
let remain = bytes - offset;
while (remain > bufferByteSize) {
await this.genNextBlock();
result.set(new Uint8Array(this.buffer), offset);
offset += bufferByteSize;
remain -= bufferByteSize;
}
if (remain === 0) {
nextBlockWait = null;
this.genNextBlock().then(resolve, reject);
return result;
}
await this.genNextBlock();
result.set(new Uint8Array(this.buffer, 0, remain), offset);
this.bufferIdx = remain;
return result;
})();
});
//이 코드를 통해 Promise 내부가 실행된다
await delay(0);
const nextBlock = await waiter;
if (nextBlockWait) {
nextBlockWait();
}
return nextBlock as Uint8Array;
}
public async nextBits(bits: number, baseBytes?: number): Promise<Uint8Array> {
await this.ready;
bits |= 0;
const bytes = (bits + 7) >> 3;
const headBits = bits & 0x7;
const result = await this.nextBytes(bytes, baseBytes);
if (headBits === 0) {
return result;
}
result[bytes - 1] &= 0xff >> (8 - headBits);
return result;
}
protected async _nextInt(bits: number): Promise<bigint> {
const buffer = await this.nextBits(bits, 8);
const dataView = new DataView(buffer.buffer);
return dataView.getBigUint64(0, true);
}
public async nextInt(max?: number): Promise<number> {
if (max === undefined || max === maxInt) {
return Number(await this._nextInt(maxRngSupportBit));
}
if (max > maxInt) {
throw new Error('Over max int');
}
if (max === 0) {
return 0;
}
if (max < 0) {
return -this.nextInt(-max);
}
const mask = calcBitMask(BigInt(max));
const bits = intBitMapMask.get(mask) as number;
let n = Number(this._nextInt(bits));
while (n > max) {
n = Number(this._nextInt(bits));
}
return n;
}
public async nextFloat1(): Promise<number> {
// eslint-disable-next-line no-constant-condition
while (true) {
const nInt = await this._nextInt(maxRngSupportBit + 1);
if (nInt < maxIntMore1) {
return Number(nInt) / maxIntMore1f;
}
if (nInt === maxIntMore1) {
return 1;
}
}
}
public static build(seed: BytesLike, stateIdx = 0): LiteHashDRBG {
return new LiteHashDRBG(seed, stateIdx);
}
}
-1
View File
@@ -1 +0,0 @@
export type Nullable<T> = T | null | undefined;
-101
View File
@@ -1,101 +0,0 @@
const convListLevel1: Record<string, Record<string, string>> = {
'ㄱ': {
'ㅅ': 'ㄳ',
},
'ㄴ': {
'ㅈ': 'ㄵ',
'ㅎ': 'ㄶ',
},
'ㄹ': {
'ㅂ': 'ㄼ',
'ㄱ': 'ㄺ',
'ㅅ': 'ㄽ',
'ㅁ': 'ㄻ',
'ㅎ': 'ㅀ',
'ㅌ': 'ㄾ',
'ㅍ': 'ㄿ',
},
'ㅂ': {
'ㅅ': 'ㅄ',
},
}
const convListLevel2: Record<string, Record<string, string>> = {
'ㄱ': {
'ㄱ': 'ㄲ',
'ㅅ': 'ㄳ',
},
'ㄴ': {
'ㅈ': 'ㄵ',
'ㅎ': 'ㄶ',
},
'ㄷ': {
'ㄷ': 'ㄸ',
},
'ㄹ': {
'ㅂ': 'ㄼ',
'ㄱ': 'ㄺ',
'ㅅ': 'ㄽ',
'ㅁ': 'ㄻ',
'ㅎ': 'ㅀ',
'ㅌ': 'ㄾ',
'ㅍ': 'ㄿ',
},
'ㅂ': {
'ㅂ': 'ㅃ',
'ㅅ': 'ㅄ',
},
'ㅅ': {
'ㅅ': 'ㅆ',
},
'ㅈ': {
'ㅈ': 'ㅉ',
}
}
function automata초성(text: string, convList: Record<string, Record<string, string>>): string{
const result: string[] = [];
let head: undefined | string = undefined;
for (const ch of text) {
if (head === undefined) {
if(!(ch in convList)){
result.push(ch);
continue;
}
head = ch;
continue;
}
const nextConv = convList[head];
if(ch in nextConv){
result.push(nextConv[ch]);
head = undefined;
continue;
}
result.push(head);
if(!(ch in convList)){
result.push(ch);
head = undefined;
continue;
}
head = ch;
}
if(head !== undefined){
result.push(head);
head = undefined;
}
return result.join('');
}
export function automata초성All(text: string): [string, string]{
return [automata초성(text, convListLevel1), automata초성(text, convListLevel2)];
}
export function automata초성Level1(text: string): string{
return automata초성(text, convListLevel1);
}
export function automata초성Level2(text: string): string {
return automata초성(text, convListLevel2);
}
-11
View File
@@ -1,11 +0,0 @@
import { combineObject } from "./combineObject.js";
export function combineArray<K extends string, V>(array: V[][], columnList: K[]): Record<K, V>[] {
const result: Record<K, V>[] = [];
for (const key of array.keys()) {
const item = array[key];
result[key] = combineObject(item, columnList);
}
return result;
}
-8
View File
@@ -1,8 +0,0 @@
export function combineObject<K extends string, V>(item: V[], columnList: K[]): Record<K, V> {
const newItem: Record<string, V> = {};
for (const columnIdx in columnList) {
const columnName = columnList[columnIdx];
newItem[columnName] = item[columnIdx];
}
return newItem;
}
@@ -1,17 +0,0 @@
import type { BytesLike } from "./BytesLike.js";
export function convertBytesLikeToArrayBuffer(data: BytesLike, encodeUTF8 = true): ArrayBuffer{
if (data instanceof ArrayBuffer) {
return data;
}
if (data instanceof Uint8Array) {
return data.buffer;
}
if (typeof(data) === 'string'){
if(encodeUTF8){
return (new TextEncoder()).encode(data);
}
return new Uint8Array(data.split('').map(s=>s.codePointAt(0) as number));
}
return data.buffer;
}
@@ -1,17 +0,0 @@
import type { BytesLike } from "./BytesLike.js";
export function convertBytesLikeToUint8Array(data: BytesLike, encodeUTF8 = true): Uint8Array {
if (data instanceof Uint8Array) {
return data;
}
if (data instanceof ArrayBuffer) {
return new Uint8Array(data);
}
if (typeof (data) === 'string') {
if(encodeUTF8){
return (new TextEncoder()).encode(data);
}
return new Uint8Array(data.split('').map(s=>s.codePointAt(0) as number));
}
return new Uint8Array(data.buffer);
}
-9
View File
@@ -1,9 +0,0 @@
import type { IDItem } from './defs.js';
export function convertIDArray<T>(array: Iterable<T>): IDItem<T>[] {
const result: IDItem<T>[] = [];
for (const id of array) {
result.push({ id });
}
return result;
}
-10
View File
@@ -1,10 +0,0 @@
export function convertIterableToMap<T extends object, K extends keyof T, V extends T[K] & (string | number | symbol)>(
values: Iterable<T>,
key: K
): Map<V, T> {
const result = new Map<V, T>();
for (const obj of values) {
result.set(obj[key] as V, obj);
}
return result;
}
-9
View File
@@ -1,9 +0,0 @@
import { automata초성All } from "./automata초성.js";
import { filter초성withAlphabet } from "./filter초성withAlphabet.js";
export function convertSearch초성(text: string): string[]{
const [filteredTextH, filteredTextA] = filter초성withAlphabet(text.replace(/\s+/g, ""));
const [filteredTextHL1, filteredTextHL2] = automata초성All(filteredTextH);
return [text, filteredTextA, filteredTextH, filteredTextHL1, filteredTextHL2];
}
-5
View File
@@ -1,5 +0,0 @@
export declare type ValuesOf<T> = T[keyof T];
export type IDItem<T> = {
id: T;
};
-7
View File
@@ -1,7 +0,0 @@
export function delay(ms: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(() => {
resolve();
}, ms);
});
}
-17
View File
@@ -1,17 +0,0 @@
export function filter초성(text: string): string {
const = [
"ㄱ", "ㄲ", "ㄴ", "ㄷ", "ㄸ", "ㄹ", "ㅁ", "ㅂ", "ㅃ",
"ㅅ", "ㅆ", "ㅇ", "ㅈ", "ㅉ", "ㅊ", "ㅋ", "ㅌ", "ㅍ", "ㅎ"
];
const result: string[] = [];
for (const char of text) {
const code = (char.codePointAt(0) ?? 0) - 44032;
if (0 <= code && code < 11172) {
result.push([~~(code / 588)]);
}
else {
result.push(char);
}
}
return result.join('');
}
-24
View File
@@ -1,24 +0,0 @@
export function filter초성withAlphabet(text: string): [string, string] {
const = [
"ㄱ", "ㄲ", "ㄴ", "ㄷ", "ㄸ", "ㄹ", "ㅁ", "ㅂ", "ㅃ",
"ㅅ", "ㅆ", "ㅇ", "ㅈ", "ㅉ", "ㅊ", "ㅋ", "ㅌ", "ㅍ", "ㅎ"
];
const alphabets = [
"r", "R", "s", "e", "E", "f", "a", "q", "Q",
"t", "T", "d", "w", "W", "c", "z", "x", "v", "g"
];
const resultH: string[] = [];
const resultA: string[] = [];
for (const char of text) {
const code = (char.codePointAt(0) ?? 0) - 44032;
if (0 <= code && code < 11172) {
resultH.push([~~(code / 588)]);
resultA.push(alphabets[~~(code / 588)]);
}
else {
resultH.push(char);
resultA.push(char);
}
}
return [resultH.join(''), resultA.join('')];
}
-18
View File
@@ -1,18 +0,0 @@
import { format, formatISO9075 } from 'date-fns';
//const DATE_TIME_FORMAT = 'yyyy-MM-dd HH:mm:ss';
const DATE_TIME_FORMAT_WITH_FRACTION = 'yyyy-MM-dd HH:mm:ss.SSS';
export function formatTime(time: Date, withFraction?:boolean): string;
export function formatTime(time: Date, format:string): string;
export function formatTime(time: Date, withFractionOrFormat:string|boolean = false): string {
if (typeof withFractionOrFormat === "string") {
return format(time, withFractionOrFormat);
}
else if(withFractionOrFormat){
return format(time, DATE_TIME_FORMAT_WITH_FRACTION);
}
else {
return formatISO9075(time);
}
}
-5
View File
@@ -1,5 +0,0 @@
import {parseISO} from 'date-fns';
export function parseTime(dateString: string): Date{
return parseISO(dateString);
}
-3
View File
@@ -1,3 +0,0 @@
export function parseYearMonth(yearMonth: number): [number, number] {
return [(yearMonth / 12) | 0, yearMonth % 12 + 1];
}
-9
View File
@@ -1,9 +0,0 @@
import type { Nullable } from './Nullable.js';
import { NotNullExpected } from "./NotNullExpected.js";
export function unwrap<T>(result: Nullable<T>): T {
if (result === null || result === undefined) {
throw new NotNullExpected();
}
return result;
}
-10
View File
@@ -1,10 +0,0 @@
import type { Nullable } from ".//Nullable.js";
import { NotNullExpected } from ".//NotNullExpected.js";
export function unwrap_any<T>(result: Nullable<unknown>): T {
if (result === null || result === undefined) {
throw new NotNullExpected();
}
return result as T;
}
-10
View File
@@ -1,10 +0,0 @@
import type { Nullable } from ".//Nullable.js";
type ErrType<T> = { new(msg?: string): T }
export function unwrap_err<T, ErrT extends Error>(result: Nullable<T>, errType: ErrType<ErrT>, errMsg?: string): T {
if (result === null || result === undefined) {
throw new errType(errMsg);
}
return result;
}