66 lines
1.6 KiB
TypeScript
66 lines
1.6 KiB
TypeScript
/**
|
|
* Generate a mock EncryptID session for auth tests.
|
|
*
|
|
* Produces an unsigned JWT (alg: "none") matching the format stored in
|
|
* localStorage under "encryptid_session".
|
|
*/
|
|
|
|
function base64url(obj: Record<string, unknown>): string {
|
|
return Buffer.from(JSON.stringify(obj))
|
|
.toString("base64url");
|
|
}
|
|
|
|
export interface MockSessionOpts {
|
|
username?: string;
|
|
userId?: string;
|
|
authLevel?: number;
|
|
}
|
|
|
|
export function createMockSession(opts: MockSessionOpts = {}) {
|
|
const {
|
|
username = "test-user",
|
|
userId = "test-user-id-0123456789abcdef0123456789abcdef",
|
|
authLevel = 3,
|
|
} = opts;
|
|
|
|
const did = `did:key:${userId.slice(0, 32)}`;
|
|
const now = Math.floor(Date.now() / 1000);
|
|
|
|
const header = base64url({ alg: "none", typ: "JWT" });
|
|
const payload = base64url({
|
|
iss: "auth.ridentity.online",
|
|
sub: userId,
|
|
aud: "rspace.online",
|
|
iat: now,
|
|
exp: now + 86400,
|
|
username,
|
|
did,
|
|
eid: { authLevel },
|
|
});
|
|
|
|
const token = `${header}.${payload}.`;
|
|
|
|
return {
|
|
token,
|
|
claims: {
|
|
iss: "auth.ridentity.online",
|
|
sub: userId,
|
|
aud: "rspace.online",
|
|
iat: now,
|
|
exp: now + 86400,
|
|
username,
|
|
did,
|
|
eid: { authLevel },
|
|
},
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Returns a JS snippet that can be passed to page.addInitScript()
|
|
* to inject the mock session into localStorage before any page JS runs.
|
|
*/
|
|
export function sessionInjectionScript(opts?: MockSessionOpts): string {
|
|
const session = createMockSession(opts);
|
|
return `localStorage.setItem("encryptid_session", ${JSON.stringify(JSON.stringify(session))});`;
|
|
}
|