36 lines
988 B
TypeScript
36 lines
988 B
TypeScript
|
|
import { createHash } from "crypto";
|
||
|
|
|
||
|
|
export type SignOptions = {
|
||
|
|
apiAppId: string;
|
||
|
|
apiSecret: string;
|
||
|
|
timestamp?: string;
|
||
|
|
};
|
||
|
|
|
||
|
|
export type SignedRequest = {
|
||
|
|
bodyString: string;
|
||
|
|
headers: Record<string, string>;
|
||
|
|
};
|
||
|
|
|
||
|
|
export function stringifyBody(payload: unknown): string {
|
||
|
|
return JSON.stringify(payload);
|
||
|
|
}
|
||
|
|
|
||
|
|
export function dreameSign(bodyString: string, timestamp: string, apiSecret: string): string {
|
||
|
|
return createHash("md5").update(Buffer.from(bodyString + timestamp + apiSecret, "utf8")).digest("hex");
|
||
|
|
}
|
||
|
|
|
||
|
|
export function buildSignedRequest(payload: unknown, options: SignOptions): SignedRequest {
|
||
|
|
const bodyString = stringifyBody(payload);
|
||
|
|
const timestamp = options.timestamp ?? Date.now().toString();
|
||
|
|
|
||
|
|
return {
|
||
|
|
bodyString,
|
||
|
|
headers: {
|
||
|
|
"content-type": "application/json",
|
||
|
|
"dreame-api-app-id": options.apiAppId,
|
||
|
|
"dreame-api-timestamp": timestamp,
|
||
|
|
"dreame-api-sign": dreameSign(bodyString, timestamp, options.apiSecret),
|
||
|
|
},
|
||
|
|
};
|
||
|
|
}
|