@sphereon/ssi-sdk.siopv2-oid4vp-rp-rest-api
Version:
167 lines • 10.2 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.verifyAuthResponseSIOPv2Endpoint = verifyAuthResponseSIOPv2Endpoint;
exports.getAuthRequestSIOPv2Endpoint = getAuthRequestSIOPv2Endpoint;
const did_auth_siop_1 = require("@sphereon/did-auth-siop");
const ssi_express_support_1 = require("@sphereon/ssi-express-support");
const ssi_types_1 = require("@sphereon/ssi-types");
const parseAuthorizationResponse = (request) => {
const contentType = request.header('content-type');
if (contentType === 'application/json') {
const payload = typeof request.body === 'string' ? JSON.parse(request.body) : request.body;
return payload;
}
if (contentType === 'application/x-www-form-urlencoded') {
const payload = request.body;
// Parse presentation_submission if it's a string
if (typeof payload.presentation_submission === 'string') {
console.log(`Supplied presentation_submission was a string instead of JSON. Correcting, but external party should fix their implementation!`);
payload.presentation_submission = JSON.parse(payload.presentation_submission);
}
// when using FORM_URL_ENCODED, vp_token comes back as string not matter whether the input was string, object or array. Handled below.
if (typeof payload.vp_token === 'string') {
const { vp_token } = payload;
// The only use case where vp_object is an object is JsonLdAsString atm. For arrays, any objects will be parsed along with the array
// (Leaving the vp_token JsonLdAsString causes problems because the original credential will remain string and will be interpreted as JWT in some parts of the code)
if ((vp_token.startsWith('[') && vp_token.endsWith(']')) || ssi_types_1.CredentialMapper.isJsonLdAsString(vp_token)) {
payload.vp_token = JSON.parse(vp_token);
}
}
return payload;
}
throw new Error(`Unsupported content type: ${contentType}. Currently only application/x-www-form-urlencoded and application/json (for direct_post) are supported`);
};
function verifyAuthResponseSIOPv2Endpoint(router, context, opts) {
var _a;
if ((opts === null || opts === void 0 ? void 0 : opts.enabled) === false) {
console.log(`verifyAuthResponse SIOP endpoint is disabled`);
return;
}
const path = (_a = opts === null || opts === void 0 ? void 0 : opts.path) !== null && _a !== void 0 ? _a : '/siop/definitions/:definitionId/auth-responses/:correlationId';
router.post(path, (0, ssi_express_support_1.checkAuth)(opts === null || opts === void 0 ? void 0 : opts.endpoint), (request, response) => __awaiter(this, void 0, void 0, function* () {
var _a, _b;
try {
const { correlationId, definitionId, tenantId, version } = request.params;
if (!correlationId || !definitionId) {
console.log(`No authorization request could be found for the given url. correlationId: ${correlationId}, definitionId: ${definitionId}`);
return (0, ssi_express_support_1.sendErrorResponse)(response, 404, 'No authorization request could be found');
}
console.log('Authorization Response (siop-sessions');
console.log(JSON.stringify(request.body, null, 2));
const definitionItems = yield context.agent.pdmGetDefinitions({ filter: [{ definitionId, tenantId, version }] });
if (definitionItems.length === 0) {
console.log(`Could not get definition ${definitionId} from agent. Will return 404`);
response.statusCode = 404;
response.statusMessage = `No definition ${definitionId}`;
return response.send();
}
const authorizationResponse = parseAuthorizationResponse(request);
console.log(`URI: ${JSON.stringify(authorizationResponse)}`);
const definitionItem = definitionItems[0];
const verifiedResponse = yield context.agent.siopVerifyAuthResponse({
authorizationResponse,
correlationId,
definitionId,
presentationDefinitions: [
{
location: (_a = opts === null || opts === void 0 ? void 0 : opts.presentationDefinitionLocation) !== null && _a !== void 0 ? _a : did_auth_siop_1.PresentationDefinitionLocation.TOPLEVEL_PRESENTATION_DEF,
definition: definitionItem.definitionPayload,
},
],
dcqlQuery: definitionItem.dcqlPayload,
});
const wrappedPresentation = (_b = verifiedResponse === null || verifiedResponse === void 0 ? void 0 : verifiedResponse.oid4vpSubmission) === null || _b === void 0 ? void 0 : _b.presentations[0];
if (wrappedPresentation) {
// const credentialSubject = wrappedPresentation.presentation.verifiableCredential[0]?.credential?.credentialSubject
// console.log(JSON.stringify(credentialSubject, null, 2))
console.log('PRESENTATION:' + JSON.stringify(wrappedPresentation.presentation, null, 2));
response.statusCode = 200;
const authorizationChallengeValidationResponse = {
presentation_during_issuance_session: verifiedResponse.correlationId,
};
if (authorizationResponse.is_first_party) {
response.setHeader('Content-Type', 'application/json');
return response.send(JSON.stringify(authorizationChallengeValidationResponse));
}
const responseRedirectURI = yield context.agent.siopGetRedirectURI({ correlationId, definitionId, state: verifiedResponse.state });
if (responseRedirectURI) {
response.setHeader('Content-Type', 'application/json');
return response.send(JSON.stringify({ redirect_uri: responseRedirectURI }));
}
// todo: delete session
}
else {
console.log('Missing Presentation (Verifiable Credentials)');
response.statusCode = 500;
response.statusMessage = 'Missing Presentation (Verifiable Credentials)';
}
return response.send();
}
catch (error) {
console.error(error);
return (0, ssi_express_support_1.sendErrorResponse)(response, 500, 'Could not verify auth status', error);
}
}));
}
function getAuthRequestSIOPv2Endpoint(router, context, opts) {
var _a;
if ((opts === null || opts === void 0 ? void 0 : opts.enabled) === false) {
console.log(`getAuthRequest SIOP endpoint is disabled`);
return;
}
const path = (_a = opts === null || opts === void 0 ? void 0 : opts.path) !== null && _a !== void 0 ? _a : '/siop/definitions/:definitionId/auth-requests/:correlationId';
router.get(path, (0, ssi_express_support_1.checkAuth)(opts === null || opts === void 0 ? void 0 : opts.endpoint), (request, response) => __awaiter(this, void 0, void 0, function* () {
var _a, _b;
try {
const correlationId = request.params.correlationId;
const definitionId = request.params.definitionId;
if (!correlationId || !definitionId) {
console.log(`No authorization request could be found for the given url. correlationId: ${correlationId}, definitionId: ${definitionId}`);
return (0, ssi_express_support_1.sendErrorResponse)(response, 404, 'No authorization request could be found');
}
const requestState = yield context.agent.siopGetAuthRequestState({
correlationId,
definitionId,
errorOnNotFound: false,
});
if (!requestState) {
console.log(`No authorization request could be found for the given url in the state manager. correlationId: ${correlationId}, definitionId: ${definitionId}`);
return (0, ssi_express_support_1.sendErrorResponse)(response, 404, `No authorization request could be found`);
}
const requestObject = yield ((_b = (_a = requestState.request) === null || _a === void 0 ? void 0 : _a.requestObject) === null || _b === void 0 ? void 0 : _b.toJwt());
console.log('JWT Request object:');
console.log(requestObject);
let error;
try {
response.statusCode = 200;
response.setHeader('Content-Type', 'application/jwt');
return response.send(requestObject);
}
catch (e) {
error = typeof e === 'string' ? e : e instanceof Error ? e.message : undefined;
return (0, ssi_express_support_1.sendErrorResponse)(response, 500, 'Could not get authorization request', e);
}
finally {
yield context.agent.siopUpdateAuthRequestState({
correlationId,
definitionId,
state: 'sent',
error,
});
}
}
catch (error) {
return (0, ssi_express_support_1.sendErrorResponse)(response, 500, 'Could not get authorization request', error);
}
}));
}
//# sourceMappingURL=siop-api-functions.js.map