@@ -10,6 +10,7 @@ import { encode as base64URLEncode } from '../util/base64url';
1010import { postMessageAll , postMessage } from './external' ;
1111import { isTokenValid , canRefreshToken } from './tokenHelpers' ;
1212import _debug from './debug' ;
13+ import retryFetch from './retryFetch' ;
1314
1415function debug ( msg : string , ...args : any [ ] ) {
1516 _debug ( `[oauthClient]: ${ msg } ` , ...args ) ;
@@ -55,13 +56,10 @@ function dbClearAuth(): Promise<any> {
5556
5657export async function initClient ( clientID : string ) {
5758 const token = await getToken ( ) ;
58- if ( isTokenValid ( token ) ) {
59+ if ( token && isTokenValid ( token ) ) {
5960 debug ( '[initClient]: using existing valid token' , token ) ;
60-
61- await postMessageAll ( {
62- type : types . MessageType . AUTH_TOKEN ,
63- payload : token as types . OAuthToken
64- } ) ;
61+ // setToken will handle setting up the refresh cycle
62+ await setToken ( token ) ;
6563 return ;
6664 } else if ( canRefreshToken ( token ) ) {
6765 debug ( '[initClient]: attempting to refresh existing token' , token ) ;
@@ -191,7 +189,8 @@ async function setToken(token: types.OAuthToken) {
191189 await dbSet ( DBKeys . TOKEN , token ) ;
192190
193191 if ( canRefreshToken ( token ) ) {
194- const expiresInMs = token . expires_in * 1000 ;
192+ const delta = Date . now ( ) - token . issued_time ;
193+ const expiresInMs = token . expires_in * 1000 - delta ;
195194 const minRefreshDelayMs = 5000 ;
196195 const maxRefreshDelayMs = 20000 ;
197196 // refresh 5 to 20 seconds before it expires
@@ -244,7 +243,7 @@ async function getServerMeta(): Promise<ServerMetadata> {
244243 }
245244
246245 const url = `${ config . OAUTH_ISSUER } /.well-known/oauth-authorization-server` ;
247- const res = await fetch ( url ) ;
246+ const res = await retryFetch ( url ) ;
248247 const meta = await res . json ( ) ;
249248 if ( ! codePointCompare ( config . OAUTH_ISSUER , meta . issuer ) ) {
250249 throw new Error (
@@ -386,7 +385,7 @@ async function doTokenExchange(params: types.OAuthCallbackResponse) {
386385 body . set ( 'redirect_uri' , cachedValues . redirectURI ) ;
387386 body . set ( 'client_id' , config . OAUTH_CLIENT_ID ) ;
388387 body . set ( 'audience' , config . CONTROLLER_HOST ) ;
389- const res = await fetch ( meta . token_endpoint , {
388+ const res = await retryFetch ( meta . token_endpoint , {
390389 method : 'POST' ,
391390 headers : {
392391 'Content-Type' : 'application/x-www-form-urlencoded'
@@ -416,7 +415,7 @@ async function doTokenRefresh(refreshToken: string) {
416415 body . set ( 'refresh_token' , refreshToken ) ;
417416 body . set ( 'client_id' , config . OAUTH_CLIENT_ID ) ;
418417 body . set ( 'audience' , config . CONTROLLER_HOST ) ;
419- const res = await fetch ( meta . token_endpoint , {
418+ const res = await retryFetch ( meta . token_endpoint , {
420419 method : 'POST' ,
421420 headers : {
422421 'Content-Type' : 'application/x-www-form-urlencoded'
0 commit comments