@hellocoop/helper-server
Version:
Hellō helper functions for server
81 lines (80 loc) • 3 kB
JavaScript
;
// creates an authorization request URL for Hellō
Object.defineProperty(exports, "__esModule", { value: true });
exports.isValidScope = isValidScope;
exports.areScopesValid = areScopesValid;
exports.createAuthRequest = createAuthRequest;
// var URLSearchParams
// export const setURLSearchParams = (u) => {
const pkce_1 = require("./pkce");
const definitions_1 = require("@hellocoop/definitions");
// import { URLSearchParams } from 'url'
function isValidScope(scope) {
return definitions_1.VALID_SCOPES.includes(scope);
}
function areScopesValid(scopes) {
return scopes.every((scope) => isValidScope(scope));
}
async function createAuthRequest(config) {
// Ensure client_id is provided (required)
if (!config.client_id) {
throw new Error('client_id is required in the authorization request.');
}
if (!config.redirect_uri) {
throw new Error('redirect_uri is required in the authorization request.');
}
// TODO check if redirect_uri is a valid URL
// TODO check if wallet is valid host or boolean
if (config.scope) {
if (!areScopesValid(config.scope))
throw new Error('One or more passed scopes are invalid.');
// add in openid scope and make unique
config.scope = Array.from(new Set([...config.scope, 'openid']));
}
if (config.response_type) {
if (!definitions_1.VALID_RESPONSE_TYPE.includes(config.response_type))
throw new Error('Invalid response_type.');
}
if (config.response_mode) {
if (!definitions_1.VALID_RESPONSE_MODE.includes(config.response_mode))
throw new Error('Invalid response_mode.');
}
const nonce = config.nonce || (0, pkce_1.uuidv4)();
let code_verifier = '';
const scopeArray = config.scope || definitions_1.DEFAULT_SCOPE;
const scope = scopeArray.join(' ');
const params = {
client_id: config.client_id,
redirect_uri: config.redirect_uri,
scope,
response_type: config.response_type || definitions_1.DEFAULT_RESPONSE_TYPE,
response_mode: config.response_mode || definitions_1.DEFAULT_RESPONSE_MODE,
nonce,
};
if (config.prompt) {
params.prompt = config.prompt;
}
if (params.response_type === 'code') {
const pkceMaterial = await (0, pkce_1.pkce)();
code_verifier = pkceMaterial.code_verifier;
params.code_challenge = pkceMaterial.code_challenge;
params.code_challenge_method = 'S256';
}
if (config.provider_hint) {
params.provider_hint = config.provider_hint.join(' ');
}
if (config.login_hint) {
params.login_hint = config.login_hint;
}
if (config.domain_hint) {
params.domain_hint = config.domain_hint;
}
const url = (config.wallet || definitions_1.PRODUCTION_WALLET)
+ definitions_1.DEFAULT_PATH
+ new URLSearchParams(params).toString();
return {
url,
nonce,
code_verifier
};
}