55 lines
1.3 KiB
TypeScript

import LogtoClient from "@logto/chrome-extension";
import { readAuthConfig } from "../../shared/auth-config";
import type { AuthClientLike } from "./types";
export function createLogtoAuthClient(): AuthClientLike {
const config = readAuthConfig();
const client = new LogtoClient({
appId: config.appId,
endpoint: config.logtoEndpoint,
resources: [config.apiResource],
scopes: config.scopes
});
return {
getAccessToken(resource?: string) {
return client.getAccessToken(resource);
},
getIdTokenClaims() {
return client.getIdTokenClaims();
},
isAuthenticated() {
return client.isAuthenticated();
},
signIn() {
return client.signIn(readChromeIdentity().getRedirectURL("/callback"));
},
signOut() {
return client.signOut(readChromeIdentity().getRedirectURL());
}
};
}
function readChromeIdentity(): {
getRedirectURL: (path?: string) => string;
} {
const identity = (
globalThis as typeof globalThis & {
chrome?: {
identity?: {
getRedirectURL?: (path?: string) => string;
};
};
}
).chrome?.identity;
if (typeof identity?.getRedirectURL !== "function") {
throw new Error("chrome.identity.getRedirectURL is unavailable");
}
return {
getRedirectURL: identity.getRedirectURL.bind(identity)
};
}