Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(browser): sign-in session storage #175

Merged
merged 1 commit into from
Feb 15, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/browser/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ module.exports = {
collectCoverageFrom: ['src/**/*.{js,jsx,ts,tsx}', '!<rootDir>/node_modules/'],
coverageReporters: ['text-summary', 'lcov'],
moduleFileExtensions: ['ts', 'js'],
setupFilesAfterEnv: ['./jest.setup.js'],
setupFilesAfterEnv: ['./jest.setup.js', 'jest-matcher-specific-error'],
testEnvironment: 'jsdom',
testPathIgnorePatterns: ['lib'],
testRegex: '(/__tests__/.*|\\.(test|spec))\\.(ts|js)$',
Expand Down
6 changes: 5 additions & 1 deletion packages/browser/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,19 @@
},
"dependencies": {
"@logto/js": "^0.0.1",
"@silverhand/essentials": "^1.1.5"
"@silverhand/essentials": "^1.1.5",
"lodash.get": "^4.4.2",
"superstruct": "^0.15.3"
},
"devDependencies": {
"@silverhand/eslint-config": "^0.7.0",
"@silverhand/ts-config": "^0.7.0",
"@types/lodash.get": "^4.4.6",
"codecov": "^3.8.3",
"eslint": "^8.8.0",
"jest": "^27.0.6",
"jest-location-mock": "^1.0.9",
"jest-matcher-specific-error": "^1.0.0",
"lint-staged": "^12.3.3",
"prettier": "^2.3.2",
"text-encoder": "^0.0.4",
Expand Down
33 changes: 33 additions & 0 deletions packages/browser/src/errors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { NormalizeKeyPaths } from '@silverhand/essentials';
import get from 'lodash.get';

const logtoClientErrorCodes = Object.freeze({
sign_in_session: {
invalid: 'Invalid sign-in session.',
},
});

export type LogtoClientErrorCode = NormalizeKeyPaths<typeof logtoClientErrorCodes>;

const getMessageByErrorCode = (errorCode: LogtoClientErrorCode): string => {
// TODO: linear issue LOG-1419
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const message = get(logtoClientErrorCodes, errorCode);

if (typeof message === 'string') {
return message;
}

return errorCode;
};

export class LogtoClientError extends Error {
code: LogtoClientErrorCode;
data: unknown;

constructor(code: LogtoClientErrorCode, data?: unknown) {
super(getMessageByErrorCode(code));
this.code = code;
this.data = data;
}
}
92 changes: 81 additions & 11 deletions packages/browser/src/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,100 @@
import LogtoClient from './index';
import { Optional } from '@silverhand/essentials';

import LogtoClient, { LogtoClientError, LogtoSignInSessionItem } from '.';

const clientId = 'client_id_value';
const endpoint = 'https://logto.dev';
const authorizationEndpoint = `${endpoint}/oidc/auth`;
const mockedCodeVerifier = 'code_verifier_value';
const mockedState = 'state_value';
const mockedSignInUri = `${authorizationEndpoint}?foo=bar`;
const redirectUri = 'http://localhost:3000/callback';
const requester = jest.fn();
const signInUri = `${authorizationEndpoint}?foo=bar`;

jest.mock('@logto/js', () => {
return {
...jest.requireActual('@logto/js'),
fetchOidcConfig: async () => ({ authorizationEndpoint }),
generateSignInUri: () => signInUri,
};
});

jest.mock('@logto/js', () => ({
...jest.requireActual('@logto/js'),
fetchOidcConfig: async () => ({ authorizationEndpoint }),
generateCodeChallenge: jest.fn().mockResolvedValue('code_challenge_value'),
generateCodeVerifier: jest.fn(() => mockedCodeVerifier),
generateSignInUri: jest.fn(() => mockedSignInUri),
generateState: jest.fn(() => mockedState),
}));

/**
* Make LogtoClient.signInSession accessible for test
*/
class LogtoClientSignInSessionAccessor extends LogtoClient {
public getSignInSessionItem(): Optional<LogtoSignInSessionItem> {
return this.signInSession;
}

public setSignInSessionItem(item: Optional<LogtoSignInSessionItem>) {
this.signInSession = item;
}
}

describe('LogtoClient', () => {
test('constructor', () => {
expect(() => new LogtoClient({ endpoint, clientId, requester })).not.toThrow();
});

describe('signInSession', () => {
test('getter should throw LogtoClientError when signInSession does not contain the required property', () => {
const signInSessionAccessor = new LogtoClientSignInSessionAccessor({
endpoint,
clientId,
requester,
});

// @ts-expect-error
signInSessionAccessor.setSignInSessionItem({
redirectUri,
codeVerifier: mockedCodeVerifier,
});

expect(() => signInSessionAccessor.getSignInSessionItem()).toMatchError(
new LogtoClientError(
'sign_in_session.invalid',
new Error('At path: state -- Expected a string, but received: undefined')
)
);
});

test('should be able to set and get the undefined item (for clearing sign-in session)', () => {
const signInSessionAccessor = new LogtoClientSignInSessionAccessor({
endpoint,
clientId,
requester,
});

// @ts-expect-error
signInSessionAccessor.setSignInSessionItem();
expect(signInSessionAccessor.getSignInSessionItem()).toBeUndefined();
});

test('should be able to set and get the correct item', () => {
const signInSessionAccessor = new LogtoClientSignInSessionAccessor({
endpoint,
clientId,
requester,
});

const logtoSignInSessionItem: LogtoSignInSessionItem = {
redirectUri,
codeVerifier: mockedCodeVerifier,
state: mockedState,
};

signInSessionAccessor.setSignInSessionItem(logtoSignInSessionItem);
expect(signInSessionAccessor.getSignInSessionItem()).toEqual(logtoSignInSessionItem);
});
});

describe('signIn', () => {
test('window.location should be correct signInUri', async () => {
const logtoClient = new LogtoClient({ endpoint, clientId, requester });
await logtoClient.signIn(redirectUri);
expect(window.location.toString()).toEqual(signInUri);
expect(window.location.toString()).toEqual(mockedSignInUri);
});
});
});
46 changes: 45 additions & 1 deletion packages/browser/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ import {
Requester,
withReservedScopes,
} from '@logto/js';
import { Optional } from '@silverhand/essentials';
import { assert, Infer, string, type } from 'superstruct';

import { LogtoClientError } from './errors';

const discoveryPath = '/oidc/.well-known/openid-configuration';
const logtoStorageItemKeyPrefix = `logto`;
Expand All @@ -29,21 +33,59 @@ export type AccessToken = {
expiresAt: number; // Unix Timestamp in seconds
};

export const LogtoSignInSessionItemSchema = type({
redirectUri: string(),
codeVerifier: string(),
state: string(),
});

export type LogtoSignInSessionItem = Infer<typeof LogtoSignInSessionItemSchema>;

export default class LogtoClient {
protected accessTokenMap = new Map<string, AccessToken>();
protected refreshToken?: string;
protected idToken?: string;
protected logtoConfig: LogtoConfig;
protected oidcConfig?: OidcConfigResponse;
protected logtoSignInSessionKey: string;

constructor(logtoConfig: LogtoConfig) {
this.logtoConfig = logtoConfig;
this.logtoSignInSessionKey = getLogtoKey(logtoConfig.clientId);
}

public get isAuthenticated() {
return Boolean(this.idToken);
}

protected get signInSession(): Optional<LogtoSignInSessionItem> {
const jsonItem = sessionStorage.getItem(this.logtoSignInSessionKey);

if (!jsonItem) {
return undefined;
}

try {
const item: unknown = JSON.parse(jsonItem);
assert(item, LogtoSignInSessionItemSchema);

return item;
} catch (error: unknown) {
throw new LogtoClientError('sign_in_session.invalid', error);
}
}

protected set signInSession(logtoSignInSessionItem: Optional<LogtoSignInSessionItem>) {
if (!logtoSignInSessionItem) {
sessionStorage.removeItem(this.logtoSignInSessionKey);

return;
}

const jsonItem = JSON.stringify(logtoSignInSessionItem);
sessionStorage.setItem(this.logtoSignInSessionKey, jsonItem);
}

public async signIn(redirectUri: string) {
const { clientId, resources, scopes: customScopes } = this.logtoConfig;
const oidcConfig = await this.getOidcConfig();
Expand All @@ -64,7 +106,7 @@ export default class LogtoClient {
resources,
});

// TODO: save redirectUri, codeVerifier and state
this.signInSession = { redirectUri, codeVerifier, state };
window.location.assign(signInUri);
}

Expand All @@ -78,3 +120,5 @@ export default class LogtoClient {
return this.oidcConfig;
}
}

export * from './errors';
5 changes: 5 additions & 0 deletions packages/browser/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@
"compilerOptions": {
"outDir": "lib",
"target": "es5",
"types": [
"node",
"jest",
"jest-matcher-specific-error"
]
},
"include": [
"src"
Expand Down
8 changes: 8 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.