Skip to content
Snippets Groups Projects
Commit 28461458 authored by Christian ZHENG's avatar Christian ZHENG
Browse files

feat(login): add pkce args but not working + stop while loop for access token

parent 1c0dd62d
Branches
Tags
2 merge requests!16feat: publish extension on marketplace with ci,!15feat(Sprint1): add authentication + directory picking + redirection link
import { createHash, randomBytes } from 'crypto';
import * as https from 'https';
import fetch from 'node-fetch';
/**
* Should not be used if object has "too much" entries
* @param copiedOject
......@@ -8,6 +10,7 @@ import fetch from 'node-fetch';
function copyOf<T>(copiedOject: T): T {
return { ...copiedOject };
}
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';
export default class OAuth2DeviceFlowConnection {
......@@ -15,47 +18,74 @@ export default class OAuth2DeviceFlowConnection {
console.log('constructor OAuth2DeviceFlowConnection');
}
async start() {
const response: CreateDeviceSessionResponse = (await fetch(
const codeChallenge = (() => {
const verifier = base64URLEncode(randomBytes(32));
console.log('code_verifier: ', verifier);
const challenge = base64URLEncode(sha256(verifier));
console.log('code_challenge: ', challenge);
return challenge;
})();
const response: DeviceAuthorizationRequestResponse = (await fetch(
'https://auth.dev.deadlock.io/auth/realms/Deadlock/protocol/openid-connect/auth/device',
{
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: 'client_id=deadlock-desktop',
body: (() => {
const params = new URLSearchParams();
params.append('client_id', 'deadlock-desktop');
// params.append('code_challenge', codeChallenge); // not working yet
// params.append('code_challenge_method', 'S256'); // not working yet
console.log('auth query body: ', params.toString());
return params.toString();
})(),
agent: new https.Agent({ rejectUnauthorized: false }),
},
).then((res) => res.json())) as CreateDeviceSessionResponse;
).then((res) => res.json())) as DeviceAuthorizationRequestResponse;
console.log(response);
// const userCode = new URL(response.verificationURIComplete as string).searchParams.get('user_code');
// const userCode = new URLSearchParams(response.verificationURIComplete as string).get('user_code');
const userCode = response.user_code;
const body = `device_code=${
response.device_code
}&client_id=${'deadlock-desktop'}&grant_type=${'urn:ietf:params:oauth:grant-type:device_code'}`;
console.log('token query body: ', body);
while (true) {
const token = await fetch(
'https://auth.dev.deadlock.io/auth/realms/Deadlock/protocol/openid-connect/token',
{
let accessToken: string = '';
let refreshToken = '';
while (!accessToken) {
const r = (await fetch('https://auth.dev.deadlock.io/auth/realms/Deadlock/protocol/openid-connect/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: body,
body: (() => {
const params = new URLSearchParams();
params.append('response_type', 'token');
params.append('device_code', response.device_code ?? '');
params.append('grant_type', 'urn:ietf:params:oauth:grant-type:device_code');
// params.append('grant_type', 'authorization_code'); // not working yet
params.append('client_id', 'deadlock-desktop');
// params.append('code_verifier', codeChallenge); // not working yet
console.log('token query body: ', params.toString());
return params.toString();
})(),
agent: new https.Agent({ rejectUnauthorized: false }),
},
).then((res) => res.json());
console.log(token);
}).then((res) => res.json())) as AuthenticationResponse;
if ((r as FailedAuthenticationReponse).error == 'authorization_pending') {
console.log('Pending ...');
await sleep(1200);
continue;
}
const fetchedAccessToken = (r as SuccessfulAuthenticationResponse).access_token;
if (fetchedAccessToken !== undefined) {
accessToken = fetchedAccessToken;
refreshToken = (r as SuccessfulAuthenticationResponse).refresh_token!;
console.log(accessToken);
}
}
console.log('end');
}
}
export interface CreateDeviceSessionResponse {
export interface DeviceAuthorizationRequestResponse {
device_code?: string;
user_code?: string;
verificationURI?: string;
......@@ -63,6 +93,33 @@ export interface CreateDeviceSessionResponse {
expiresIn?: number;
interval?: number;
}
interface SuccessfulAuthenticationResponse {
access_token?: string;
expires_in?: number;
'not-before-policy'?: number;
refresh_expires_in: number;
refresh_token?: string;
scope?: string;
session_state?: string;
token_type?: 'Bearer' | string;
}
interface FailedAuthenticationReponse {
error?: string;
error_description?: string;
}
export type AuthenticationResponse = SuccessfulAuthenticationResponse | FailedAuthenticationReponse;
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function base64URLEncode(str) {
return str.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
}
function sha256(buffer) {
return createHash('sha256').update(buffer).digest();
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment