Skip to content

Commit 0b5bdf3

Browse files
committed
Switch from Node.js crypto to Web Crypto, remove error on browser version
1 parent 756d856 commit 0b5bdf3

File tree

1 file changed

+26
-12
lines changed

1 file changed

+26
-12
lines changed

src/token.ts

Lines changed: 26 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@ import { TokenSearchRules, TokenOptions } from "./types";
22
import { MeiliSearchError } from "./errors";
33
import { validateUuid4 } from "./utils";
44

5-
function encode64(data: any) {
6-
return Buffer.from(JSON.stringify(data)).toString("base64");
5+
function encode64(data: unknown): string {
6+
return btoa(JSON.stringify(data))
77
}
88

99
/**
@@ -17,16 +17,30 @@ function encode64(data: any) {
1717
async function sign(
1818
apiKey: string,
1919
encodedHeader: string,
20-
encodedPayload: string,
21-
) {
22-
const { createHmac } = await import("node:crypto");
23-
24-
return createHmac("sha256", apiKey)
25-
.update(`${encodedHeader}.${encodedPayload}`)
26-
.digest("base64")
27-
.replace(/\+/g, "-")
28-
.replace(/\//g, "_")
29-
.replace(/=/g, "");
20+
encodedPayload: string
21+
): Promise<string> {
22+
const textEncoder = new TextEncoder()
23+
24+
const cryptoKey = await crypto.subtle.importKey(
25+
'raw',
26+
textEncoder.encode(apiKey),
27+
{ name: 'HMAC', hash: 'SHA-256' },
28+
false,
29+
['sign']
30+
)
31+
32+
const signature = await crypto.subtle.sign(
33+
'HMAC',
34+
cryptoKey,
35+
textEncoder.encode(`${encodedHeader}.${encodedPayload}`)
36+
)
37+
38+
const digest = btoa(String.fromCharCode(...new Uint8Array(signature)))
39+
.replace(/\+/g, '-')
40+
.replace(/\//g, '_')
41+
.replace(/=/g, '')
42+
43+
return digest
3044
}
3145

3246
/**

0 commit comments

Comments
 (0)