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

Sebankid #2

Merged
merged 6 commits into from
Jul 7, 2022
Merged
Show file tree
Hide file tree
Changes from 4 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 .storybook/preview.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export const parameters = {
domain: {
name: 'Domain',
description: 'Criipto Verify domain',
defaultValue: 'samples.criipto.id'
defaultValue: 'samples.criipto.io'
},
clientID: {
name: 'Client ID',
Expand Down
6 changes: 3 additions & 3 deletions package-lock.json

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

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,6 @@
},
"homepage": "https://github.com/criipto/criipto-verify-react#readme",
"dependencies": {
"@criipto/auth-js": "^2.1.6"
"@criipto/auth-js": "^2.2.1"
}
}
45 changes: 45 additions & 0 deletions src/components/AuthMethodButton/AuthMethodButton.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import React from 'react';
import { ComponentStory, ComponentMeta } from '@storybook/react';

import AuthMethodButton from './AuthMethodButton';
import CriiptoVerifyProvider from '../../provider';
import { acrValueToTitle } from '../../utils';
import StoryResponseRenderer from '../../stories/StoryResponseRenderer';

export default {
title: 'Components/AuthMethodButton',
argTypes: {
completionStrategy: {
name: 'Completion strategy',
control: 'select',
defaultValue: 'client',
options: ['client', 'openidprovider']
},
response: {
name: 'Response mode',
control: 'select',
defaultValue: 'token',
options: ['token', 'code']
}
}
} as ComponentMeta<typeof AuthMethodButton>;

// More on component templates: https://storybook.js.org/docs/react/writing-stories/introduction#using-args
const Template: ComponentStory<typeof AuthMethodButton> = (args, {globals}) => {
return (
<CriiptoVerifyProvider completionStrategy={(args as any).completionStrategy} response={(args as any).response} domain={globals.domain} clientID={globals.clientID} redirectUri="https://httpbin.org/get">
<StoryResponseRenderer>
<AuthMethodButton {...args}>
{acrValueToTitle('en', args.acrValue).title}<br />
{acrValueToTitle('en', args.acrValue).subtitle}
</AuthMethodButton>
</StoryResponseRenderer>
</CriiptoVerifyProvider>
);
};

export const SEBankIDSameDeviceButton = Template.bind({});
SEBankIDSameDeviceButton.args = {
acrValue: 'urn:grn:authn:se:bankid:same-device'
};
SEBankIDSameDeviceButton.storyName = "se:bankid:same-device";
13 changes: 13 additions & 0 deletions src/components/AuthMethodButton/AuthMethodButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import sofort from './logos/sofort.png';

import './AuthMethodButton.css';
import CriiptoVerifyContext from '../../context';
import SEBankIDSameDeviceButton from '../SEBankIDSameDeviceButton';

interface ButtonProps {
className?: string,
Expand Down Expand Up @@ -63,6 +64,18 @@ export default function AuthMethodButton(props: AuthMethodButtonProps) {
.catch(console.error);
}, [props.href, acrValue]);

if (acrValue === 'urn:grn:authn:se:bankid:same-device') {
return (
<SEBankIDSameDeviceButton
redirectUri={props.redirectUri}
href={href} className={className}
>
{acrValueToLogo(acrValue) ? <img src={acrValueToLogo(acrValue)} alt="" /> : null}
<span>{props.children}</span>
</SEBankIDSameDeviceButton>
);
}

if (href) {
return (
<AnchorButton {...props} href={href} className={className}>
Expand Down
21 changes: 16 additions & 5 deletions src/components/AuthMethodSelector/AuthMethodSelector.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,27 @@ import CriiptoVerifyProvider from '../../provider';

export default {
title: 'Components/AuthMethodSelector',
component: AuthMethodSelector,
component: AuthMethodSelector
} as ComponentMeta<typeof AuthMethodSelector>;

// More on component templates: https://storybook.js.org/docs/react/writing-stories/introduction#using-args
const Template: ComponentStory<typeof AuthMethodSelector> = (args, {globals}) => {
const ClientTemplate: ComponentStory<typeof AuthMethodSelector> = (args, {globals}) => {
return (
<CriiptoVerifyProvider domain={globals.domain} clientID={globals.clientID} redirectUri="https://httpbin.org/get">
<CriiptoVerifyProvider completionStrategy="client" domain={globals.domain} clientID={globals.clientID} redirectUri="https://httpbin.org/get">
<AuthMethodSelector {...args} />
</CriiptoVerifyProvider>
);
};

export const Default = Template.bind({});
const OpenIDProviderTemplate: ComponentStory<typeof AuthMethodSelector> = (args, {globals}) => {
return (
<CriiptoVerifyProvider completionStrategy="openidprovider" domain={globals.domain} clientID={globals.clientID} redirectUri="https://httpbin.org/get">
<AuthMethodSelector {...args} />
</CriiptoVerifyProvider>
);
};

export const Default = ClientTemplate.bind({});
Default.storyName ="Completion Strategy: Client (default)"

export const OpenIDProviderCompletionStrategy = OpenIDProviderTemplate.bind({});
OpenIDProviderCompletionStrategy.storyName ="Completion Strategy: OpenID Provider"
9 changes: 5 additions & 4 deletions src/components/AuthMethodSelector/AuthMethodSelector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,17 @@ interface Props {
}

export default function AuthMethodSelector(props: Props) {
const context = useContext(CriiptoVerifyContext);
const {fetchOpenIDConfiguration} = useContext(CriiptoVerifyContext);
const language = props.language || 'en';
const [configuration, setConfiguration] = useState<OpenIDConfiguration | null>(null);

useEffect(() => {
if (props.acrValues) return;

(async () => {
const configuration = await context.fetchOpenIDConfiguration();
setConfiguration(configuration);
setConfiguration(await fetchOpenIDConfiguration());
})();
}, []);
}, [props.acrValues]);

const acrValues = filterAcrValues(props.acrValues ?? configuration?.acr_values_supported ?? []);

Expand Down
159 changes: 159 additions & 0 deletions src/components/SEBankIDSameDeviceButton/SEBankIDSameDeviceButton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
import { PKCE, AuthorizeResponse } from '@criipto/auth-js';
import React, {useCallback, useContext, useEffect, useState} from 'react';
import CriiptoVerifyContext from '../../context';
import { getMobileOS } from '../../device';
import usePageVisibility from '../../hooks/usePageVisibility';

interface Props {
className: string
children: React.ReactNode
href?: string
redirectUri?: string
}

interface Links {
cancelUrl: string
completeUrl: string
pollUrl: string
launchLinks: {
customFileHandlerUrl: string
universalLink: string
}
}

const mobileOS = getMobileOS();

function searchParamsToPOJO(input: URLSearchParams) {
return Array.from(input.keys()).reduce((memo : {[key: string]: string}, key) => {
memo[key] = input.get(key)!;
return memo;
}, {});
}

export default function SEBankIDSameDeviceButton(props: Props) {
const [href, setHref] = useState(props.href);
const [links, setLinks] = useState<Links | null>(null);
const [pkce, setPKCE] = useState<PKCE | undefined>(undefined);
const [error, setError] = useState<string | null>(null);
const [initiated, setInitiated] = useState(false);
const {buildAuthorizeUrl, completionStrategy, generatePKCE, domain, handleResponse} = useContext(CriiptoVerifyContext);
const {redirectUri} = props;

const reset = () => {
setPKCE(undefined);
setLinks(null);
setHref(props.href);
};

const handleComplete = useCallback(async (completeUrl: string) => {
const required = {pkce};
reset();

const completeResponse = await fetch(completeUrl);
if (completeResponse.status >= 400) {
setError(await completeResponse.text());
return;
}

const {location} : {location: string} = await completeResponse.json();
if (completionStrategy === 'openidprovider') {
window.location.href = location;
return;
}
const url = new URL(location);
const params = searchParamsToPOJO(url.searchParams) as AuthorizeResponse;

await handleResponse(params, {
pkce: required.pkce,
redirectUri: redirectUri
})
}, [completionStrategy, pkce]);

// Mobile visibility scenario
usePageVisibility(async () => {
if (!links || !mobileOS) return;

handleComplete(links.completeUrl);
}, [links]);

// Desktop polling scenario
useEffect(() => {
if (!links) return;
if (mobileOS) return;
if (!initiated) return;

let timeout : string | undefined;
const poll = async () => {
const response = await fetch(links.pollUrl);

if (response.status === 202) {
setTimeout(poll, 1000);
return;
} else if (response.status >= 400) {
const error = await response.text();
setError(error);
return;
} else {
const {targetUrl} = await response.json();
await handleComplete(`https://${domain}${targetUrl}`);
return;
}
};

setTimeout(poll, 1000);
return () => {
if (timeout) clearTimeout(timeout);
};
}, [links, initiated]);

const refresh = useCallback(async () => {
console.log('SEBankID: Refresh authorize url');
const pkce = await generatePKCE();

buildAuthorizeUrl({
acrValues: 'urn:grn:authn:se:bankid:same-device',
loginHint: 'appswitch:browser',
responseMode: 'json',
pkce,
redirectUri
}).then(url => {
return fetch(url).then(response => response.json() as Promise<Links>);
})
.then(links => {
setPKCE(pkce || undefined);
setLinks(links);
const redirect = mobileOS === 'ios' ? encodeURIComponent(window.location.href) : 'null';
setHref(`${mobileOS ? links.launchLinks.universalLink : links.launchLinks.customFileHandlerUrl}&redirect=${redirect}`);
})
.catch(console.error);
}, [buildAuthorizeUrl, redirectUri]);

// Generate URL on first button render
useEffect(() => {
refresh();
}, [refresh]);

// Continously fetch new autostart token if UI is open for a long time
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could this potentially trigger while the BankID app is in foreground on iOS?

Would explain the error message seen.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sgryt Hmm maybe if the onclick handler doesnt fire on iOS actually, could be it!

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sgryt Latest commit disables the refetch.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Did not change the observed behavior, I’m afraid.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But could it be the other way around - in the sense that the displayed response is from before the flow is completed in the BankID app ?

Copy link
Contributor

@sgryt sgryt Jul 6, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IIRC, the reason we had to not poll in the HTML UI was because iOS lets JS continue to run when Safari is backgrounded.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When does setInterval run the first invocation of the specified function ?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sgryt We don't poll per say in the device flows, the intent is simply to refresh links if you're idle on the page so that the order doesn't expire.

We also automatically stop the refreshing as soon as the user lcicks on the button.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

setInterval runs on the tail-end, so doesn't execute untill the first interval has passed.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sgryt Lets debug live with ngrok and slack-huddle tomorrow, will be easier.

useEffect(() => {
const interval = setInterval(() => {
if (initiated) return;
refresh();
}, 25000);
return () => clearInterval(interval);
}, [refresh, initiated]);

// Track when the button is clicked to stop refreshing URL
const handleClick = () => {
setInitiated(true);
setError(null);
}

return (
<React.Fragment>
<a className={`criipto-verify-button ${props.className}`} href={href} onClick={handleClick}>
{props.children}
</a>
{error && <p>{error}</p>}
</React.Fragment>
)
}
3 changes: 3 additions & 0 deletions src/components/SEBankIDSameDeviceButton/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"main": "./SEBankIDSameDeviceButton.tsx"
}
19 changes: 16 additions & 3 deletions src/context.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
import {OpenIDConfiguration, AuthorizeUrlParamsOptional} from '@criipto/auth-js';
import CriiptoAuth, {OpenIDConfiguration, AuthorizeUrlParamsOptional, PKCE, AuthorizeResponse} from '@criipto/auth-js';
import { createContext } from 'react';
import { Result } from './provider';

export interface CriiptoVerifyContextInterface {
loginWithRedirect: () => Promise<void>,
fetchOpenIDConfiguration: () => Promise<OpenIDConfiguration>,
buildAuthorizeUrl: (options?: AuthorizeUrlParamsOptional) => Promise<string>
buildAuthorizeUrl: (options?: AuthorizeUrlParamsOptional) => Promise<string>,
generatePKCE: () => Promise<PKCE | undefined>,
handleResponse: (response: AuthorizeResponse, params: {pkce?: PKCE, redirectUri?: string}) => Promise<void>,
responseType: 'token' | 'code'
completionStrategy: 'client' | 'openidprovider',
result: Result | null
domain: string
}

/**
Expand All @@ -20,7 +27,13 @@ const stub = (): never => {
const initialContext = {
loginWithRedirect: stub,
fetchOpenIDConfiguration: stub,
buildAuthorizeUrl: stub
buildAuthorizeUrl: stub,
generatePKCE: stub,
handleResponse: stub,
responseType: 'token' as 'token' | 'code',
completionStrategy: 'client' as 'client' | 'openidprovider',
result: null,
domain: ''
};

const CriiptoVerifyContext = createContext<CriiptoVerifyContextInterface>(initialContext);
Expand Down
21 changes: 21 additions & 0 deletions src/device.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
function testUA(pattern: RegExp) {
return pattern.test(navigator.userAgent);
};
export function isiOS() {
return testUA(/iPad|iPhone|iPod/) && !(window as any).MSStream;
};

export function isiOSSafari() {
return isiOS() && !testUA(/ CriOS\/[.0-9]*/);
};

export function isAndroid() { return testUA(/Android/); };

export type MobileOS = 'ios' | 'android';

export function getMobileOS() : MobileOS | null {
if (isiOS()) return 'ios';
if (isAndroid()) return 'android';

return null;
}
Loading