Last active
August 3, 2024 21:23
-
-
Save MrAntix/90be1996f0386135c2cae2ac12764385 to your computer and use it in GitHub Desktop.
A signing provider function written in typesript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* A reusable signing function using the token passed to a provider | |
* | |
* @param data data to sign | |
* @returns Base64 signature | |
*/ | |
export type TokenSign = (data: string) => Promise<string>; | |
/* | |
* Constants for signing | |
*/ | |
export const SIGNING: { | |
MIN_TOKEN_LENGTH: number, | |
ALGORITHM: AlgorithmIdentifier | RsaPssParams | EcdsaParams | |
} = { | |
MIN_TOKEN_LENGTH: 24, | |
ALGORITHM: { name: 'HMAC', hash: 'SHA-512' } | |
}; | |
import { SIGNING } from "./SIGNING"; | |
import { TokenSign } from "./TokenSign"; | |
/** | |
* provides a signing function using the token passed | |
* | |
* @param token token to use for signing | |
* @returns a signing function | |
*/ | |
export function provideSign( | |
token: string, | |
algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams = SIGNING.ALGORITHM | |
): TokenSign { | |
if (token == null | |
|| typeof token !== 'string' | |
|| token.trim().length < SIGNING.MIN_TOKEN_LENGTH) | |
throw new Error(`Token for signing must be at least ${SIGNING.MIN_TOKEN_LENGTH} characters long`); | |
const encoder = new TextEncoder(); | |
const getKey = crypto.subtle | |
.importKey( | |
'raw', | |
encoder.encode(token), | |
algorithm, | |
false, | |
['sign'] | |
); | |
return async data => { | |
if (data == null | |
|| typeof data !== 'string' | |
|| data.trim().length === 0) | |
throw new Error('Data to sign must be provided'); | |
const signature = await crypto.subtle | |
.sign( | |
algorithm, | |
await getKey, | |
encoder.encode(data) | |
); | |
return btoa(String.fromCharCode(...new Uint8Array(signature))); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment