meilisearch
Version:
The Meilisearch JS client for Node.js and the browser.
57 lines (56 loc) • 1.89 kB
JavaScript
//#region src/token.ts
function e(e) {
let { searchRules: t = ["*"], algorithm: n = "HS256", force: r = !1, ...i } = e;
return {
searchRules: t,
algorithm: n,
force: r,
...i
};
}
var t = /^[0-9a-f]{8}\b(?:-[0-9a-f]{4}\b){3}-[0-9a-f]{12}$/i;
function n(e) {
return t.test(e);
}
function r(e) {
return btoa(typeof e == "string" ? e : JSON.stringify(e));
}
var i = new TextEncoder();
async function a({ apiKey: e, algorithm: t }, n, r) {
let a = await crypto.subtle.importKey("raw", i.encode(e), {
name: "HMAC",
hash: `SHA-${t.slice(2)}`
}, !1, ["sign"]), o = await crypto.subtle.sign("HMAC", a, i.encode(`${r}.${n}`));
return btoa(String.fromCharCode(...new Uint8Array(o))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
}
function o({ algorithm: e }) {
return r({
alg: e,
typ: "JWT"
}).replace(/=/g, "");
}
function s({ searchRules: e, apiKeyUid: t, expiresAt: i }) {
if (!n(t)) throw Error("the uid of your key is not a valid UUIDv4");
let a = {
searchRules: e,
apiKeyUid: t
};
return i !== void 0 && (a.exp = typeof i == "number" ? i : Math.floor(i.getTime() / 1e3)), r(a).replace(/=/g, "");
}
function c() {
if (typeof navigator < "u" && "userAgent" in navigator) {
let { userAgent: e } = navigator;
if (e.startsWith("Node") || e.startsWith("Deno") || e.startsWith("Bun") || e.startsWith("Cloudflare-Workers")) return;
}
let e = globalThis.process?.versions;
if (!(e !== void 0 && Object.hasOwn(e, "node"))) throw Error("failed to detect a server-side environment; do not generate tokens on the frontend in production!\nuse the `force` option to disable environment detection, consult the documentation (Use at your own risk!)");
}
async function l(t) {
let n = e(t);
n.force || c();
let r = s(n), i = o(n);
return `${i}.${r}.${await a(n, r, i)}`;
}
//#endregion
export { l as generateTenantToken };
//# sourceMappingURL=token.js.map