@sphereon/ssi-sdk.oid4vci-issuer
Version:
959 lines (952 loc) • 36.3 kB
JavaScript
;
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// plugin.schema.json
var require_plugin_schema = __commonJS({
"plugin.schema.json"(exports, module2) {
module2.exports = {
IDidAuthSiopOpAuthenticator: {
components: {
schemas: {
IGetSiopSessionArgs: {
type: "object",
properties: {
sessionId: {
type: "string"
},
additionalProperties: false
},
required: ["sessionId"],
description: "Arguments needed for {@link DidAuthSiopOpAuthenticator.getSessionForSiop } "
},
IRegisterSiopSessionArgs: {
type: "object",
properties: {
identifier: {
type: "object",
properties: {
did: {
type: "string"
},
alias: {
type: "string"
},
provider: {
type: "string"
},
controllerKeyId: {
type: "string"
},
keys: {
type: "array",
items: {
type: "object",
properties: {
additionalProperties: true
}
}
},
services: {
type: "array",
items: {
type: "object",
properties: {
additionalProperties: true
}
}
}
},
additionalProperties: false,
required: ["did", "provider", "keys", "services"]
},
sessionId: {
type: "string"
},
expiresIn: {
type: "number"
},
additionalProperties: false
},
required: ["identifier"],
description: "Arguments needed for {@link DidAuthSiopOpAuthenticator.registerSessionForSiop } "
},
IRemoveSiopSessionArgs: {
type: "object",
properties: {
sessionId: {
type: "string"
},
additionalProperties: false
},
required: ["sessionId"],
description: "Arguments needed for {@link DidAuthSiopOpAuthenticator.removeSessionForSiop } "
},
IAuthenticateWithSiopArgs: {
type: "object",
properties: {
sessionId: {
type: "string"
},
stateId: {
type: "string"
},
redirectUrl: {
type: "string"
},
additionalProperties: false
},
required: ["sessionId", "stateId", "redirectUrl"],
description: "Arguments needed for {@link DidAuthSiopOpAuthenticator.authenticateWithSiop } "
},
IResponse: {
type: "object",
properties: {
status: {
type: "number"
},
additionalProperties: true
},
required: ["status"],
description: "Result of {@link DidAuthSiopOpAuthenticator.authenticateWithSiop & DidAuthSiopOpAuthenticator.sendSiopAuthenticationResponse } "
},
IGetSiopAuthenticationRequestFromRpArgs: {
type: "object",
properties: {
sessionId: {
type: "string"
},
stateId: {
type: "string"
},
redirectUrl: {
type: "string"
},
additionalProperties: false
},
required: ["sessionId", "stateId", "redirectUrl"],
description: "Arguments needed for {@link DidAuthSiopOpAuthenticator.getSiopAuthenticationRequestFromRP } "
},
ParsedAuthenticationRequestURI: {
type: "object",
properties: {
jwt: {
type: "string"
},
requestPayload: {
type: "object",
properties: {
additionalProperties: true
}
},
registration: {
type: "object",
properties: {
additionalProperties: true
}
},
additionalProperties: false
},
required: ["jwt", "requestPayload", "registration"],
description: "Result of {@link DidAuthSiopOpAuthenticator.getSiopAuthenticationRequestFromRP } "
},
IGetSiopAuthenticationRequestDetailsArgs: {
type: "object",
properties: {
sessionId: {
type: "string"
},
verifiedAuthenticationRequest: {
type: "object",
properties: {
additionalProperties: true
}
},
credentialFilter: {
type: "object",
properties: {
additionalProperties: true
}
},
additionalProperties: false
},
required: ["sessionId", "verifiedAuthenticationRequest"],
description: "Arguments needed for {@link DidAuthSiopOpAuthenticator.getSiopAuthenticationRequestDetails } "
},
IAuthRequestDetails: {
type: "object",
properties: {
id: {
type: "string"
},
alsoKnownAs: {
type: "array",
items: {
type: "string"
}
},
vpResponseOpts: {
type: "object",
properties: {
additionalProperties: true
}
},
additionalProperties: false
},
required: ["id", "vpResponseOpts"],
description: "Result of {@link DidAuthSiopOpAuthenticator.getSiopAuthenticationRequestDetails } "
},
IVerifySiopAuthenticationRequestUriArgs: {
type: "object",
properties: {
sessionId: {
type: "string"
},
ParsedAuthenticationRequestURI: {
type: "object",
properties: {
additionalProperties: true
}
},
additionalProperties: false
},
required: ["sessionId", "ParsedAuthenticationRequestURI"],
description: "Arguments needed for {@link DidAuthSiopOpAuthenticator.verifySiopAuthenticationRequestURI } "
},
VerifiedAuthorizationRequest: {
type: "object",
properties: {
payload: {
type: "object",
properties: {
additionalProperties: true
}
},
presentationDefinitions: {
type: "object",
properties: {
additionalProperties: true
}
},
verifyOpts: {
type: "object",
properties: {
additionalProperties: true
}
},
additionalProperties: false
},
required: ["payload", "verifyOpts"],
description: "Result of {@link DidAuthSiopOpAuthenticator.verifySiopAuthenticationRequestURI } "
},
ISendSiopAuthenticationResponseArgs: {
type: "object",
properties: {
sessionId: {
type: "string"
},
verifiedAuthenticationRequest: {
type: "object",
properties: {
additionalProperties: true
}
},
verifiablePresentationResponse: {
type: "object",
properties: {
additionalProperties: true
}
},
additionalProperties: false
},
required: ["sessionId", "verifiedAuthenticationRequest"],
description: "Arguments needed for {@link DidAuthSiopOpAuthenticator.sendSiopAuthenticationResponse } "
}
},
methods: {
getSessionForSiop: {
description: "Get SIOP session",
arguments: {
$ref: "#/components/schemas/IGetSiopSessionArgs"
},
returnType: "object"
},
registerSessionForSiop: {
description: "Register SIOP session",
arguments: {
$ref: "#/components/schemas/IRegisterSiopSessionArgs"
},
returnType: "object"
},
removeSessionForSiop: {
description: "Remove SIOP session",
arguments: {
$ref: "#/components/schemas/IRemoveSiopSessionArgs"
},
returnType: "boolean"
},
authenticateWithSiop: {
description: "Authenticate using DID Auth SIOP",
arguments: {
$ref: "#/components/schemas/IAuthenticateWithSiopArgs"
},
returnType: {
$ref: "#/components/schemas/Response"
}
},
getSiopAuthenticationRequestFromRP: {
description: "Get authentication request from RP",
arguments: {
$ref: "#/components/schemas/IGetSiopAuthenticationRequestFromRpArgs"
},
returnType: {
$ref: "#/components/schemas/ParsedAuthenticationRequestURI"
}
},
getSiopAuthenticationRequestDetails: {
description: "Get authentication request details",
arguments: {
$ref: "#/components/schemas/IGetSiopAuthenticationRequestDetailsArgs"
},
returnType: {
$ref: "#/components/schemas/IAuthRequestDetails"
}
},
verifySiopAuthenticationRequestURI: {
description: "Verify authentication request URI",
arguments: {
$ref: "#/components/schemas/IVerifySiopAuthenticationRequestUriArgs"
},
returnType: {
$ref: "#/components/schemas/VerifiedAuthorizationRequest"
}
},
sendSiopAuthenticationResponse: {
description: "Send authentication response",
arguments: {
$ref: "#/components/schemas/ISendSiopAuthenticationResponseArgs"
},
returnType: {
$ref: "#/components/schemas/IRequiredContext"
}
}
}
}
}
};
}
});
// src/index.ts
var index_exports = {};
__export(index_exports, {
IssuerInstance: () => IssuerInstance,
OID4VCIIssuer: () => OID4VCIIssuer,
createAuthRequestUriCallback: () => createAuthRequestUriCallback,
createVciIssuer: () => createVciIssuer,
createVciIssuerBuilder: () => createVciIssuerBuilder,
createVerifyAuthResponseCallback: () => createVerifyAuthResponseCallback,
getAccessTokenKeyRef: () => getAccessTokenKeyRef,
getAccessTokenSignerCallback: () => getAccessTokenSignerCallback,
getCredentialSignerCallback: () => getCredentialSignerCallback,
getJwtVerifyCallback: () => getJwtVerifyCallback,
schema: () => schema
});
module.exports = __toCommonJS(index_exports);
// src/agent/OID4VCIIssuer.ts
var import_oid4vci_common = require("@sphereon/oid4vci-common");
var import_oid4vci_issuer2 = require("@sphereon/oid4vci-issuer");
var import_oid4vci_client = require("@sphereon/oid4vci-client");
var import_ssi_sdk_ext3 = require("@sphereon/ssi-sdk-ext.did-utils");
// src/functions.ts
var import_oid4vci_issuer = require("@sphereon/oid4vci-issuer");
var import_ssi_sdk_ext = require("@sphereon/ssi-sdk-ext.did-utils");
var import_ssi_sdk_ext2 = require("@sphereon/ssi-sdk-ext.identifier-resolution");
var import_ssi_sdk = require("@sphereon/ssi-sdk.agent-config");
var import_ssi_types = require("@sphereon/ssi-types");
var import_utils = require("@veramo/utils");
var import_did_jwt = require("did-jwt");
var import_jwt_decode = require("jwt-decode");
var import_cross_fetch = __toESM(require("cross-fetch"), 1);
var import_did_auth_siop = require("@sphereon/did-auth-siop");
function getJwtVerifyCallback({ verifyOpts }, _context) {
return async (args) => {
const resolver = (0, import_ssi_sdk_ext.getAgentResolver)(_context, {
resolverResolution: true,
uniresolverResolution: true,
localResolution: true
});
verifyOpts = {
...verifyOpts,
resolver: verifyOpts?.resolver
};
if (!verifyOpts?.resolver || typeof verifyOpts?.resolver?.resolve !== "function") {
verifyOpts.resolver = resolver;
}
const result = await _context.agent.jwtVerifyJwsSignature({
jws: args.jwt
});
if (!result.error) {
const identifier = result.jws.signatures[0].identifier;
if (!identifier) {
return Promise.reject(Error("the jws did not contain a signature with an identifier"));
}
const jwkInfo = identifier.jwks[0];
if (!jwkInfo) {
return Promise.reject(Error(`the identifier of type ${identifier.method} is missing jwks (ExternalJwkInfo)`));
}
const { alg: alg2 } = jwkInfo.jwk;
const header = (0, import_jwt_decode.jwtDecode)(args.jwt, {
header: true
});
const payload = (0, import_jwt_decode.jwtDecode)(args.jwt, {
header: false
});
const kid2 = args.kid ?? header.kid;
const jwk = jwkInfo.jwk;
return {
alg: alg2,
...identifier,
jwt: {
header,
payload
},
...kid2 && {
kid: kid2
},
...jwk && {
jwk
}
};
}
const decodedJwt = await (0, import_did_jwt.decodeJWT)(args.jwt);
const kid = args.kid ?? decodedJwt.header.kid;
if (!kid || !kid.startsWith("did:")) {
return {
alg: decodedJwt.header.alg,
jwt: decodedJwt
};
}
const did = kid.split("#")[0];
const didResult = await (0, import_did_jwt.verifyJWT)(args.jwt, verifyOpts);
if (!didResult.verified) {
console.log(`JWT invalid: ${args.jwt}`);
throw Error("JWT did not verify successfully");
}
const didResolution = await resolver.resolve(did);
if (!didResolution || !didResolution.didDocument) {
throw Error(`Could not resolve did: ${did}, metadata: ${didResolution?.didResolutionMetadata}`);
}
const alg = decodedJwt.header.alg;
return {
alg,
kid,
did,
didDocument: didResolution.didDocument,
jwt: decodedJwt
};
};
}
__name(getJwtVerifyCallback, "getJwtVerifyCallback");
async function getAccessTokenKeyRef(opts, context) {
let identifier = (0, import_ssi_sdk_ext2.legacyKeyRefsToIdentifierOpts)(opts);
return await context.agent.identifierManagedGet(identifier);
}
__name(getAccessTokenKeyRef, "getAccessTokenKeyRef");
async function getAccessTokenSignerCallback(opts, context) {
const signer = /* @__PURE__ */ __name(async (data) => {
let dataString, encoding;
const resolution = await (0, import_ssi_sdk_ext2.legacyKeyRefsToIdentifierOpts)(opts);
const keyRef = resolution.kmsKeyRef;
if (!keyRef) {
throw Error("Cannot sign access tokens without a key ref");
}
if (typeof data === "string") {
dataString = data;
encoding = void 0;
} else {
dataString = (0, import_utils.bytesToBase64)(data);
encoding = "base64";
}
return context.agent.keyManagerSign({
keyRef,
data: dataString,
encoding
});
}, "signer");
async function accessTokenSignerCallback(jwt, kid) {
const issuer = opts.idOpts?.issuer ?? (typeof opts.idOpts?.identifier === "string" ? opts.idOpts.identifier : opts.didOpts?.idOpts?.identifier?.toString() ?? opts?.iss);
if (!issuer) {
throw Error("No issuer configured for access tokens");
}
let kidHeader = jwt?.header?.kid ?? kid;
if (!kidHeader) {
if (opts.idOpts?.method === "did" || opts.idOpts?.method === "kid" || typeof opts.didOpts?.idOpts.identifier === "string" && opts.didOpts?.idOpts?.identifier?.startsWith("did:")) {
kidHeader = opts.idOpts?.kid ?? opts.didOpts?.idOpts?.kid ?? opts?.didOpts?.identifierOpts?.kid;
}
}
return await (0, import_did_jwt.createJWT)(jwt.payload, {
signer,
issuer
}, {
...jwt.header,
...kidHeader && {
kid: kidHeader
},
typ: "JWT"
});
}
__name(accessTokenSignerCallback, "accessTokenSignerCallback");
return accessTokenSignerCallback;
}
__name(getAccessTokenSignerCallback, "getAccessTokenSignerCallback");
async function getCredentialSignerCallback(idOpts, context) {
async function issueVCCallback(args) {
const { jwtVerifyResult, format, statusLists } = args;
const credential = args.credential;
let proofFormat;
const resolution = await context.agent.identifierManagedGet(idOpts);
proofFormat = format?.includes("ld") ? "lds" : "jwt";
const issuer = resolution.issuer ?? resolution.kmsKeyRef;
if (import_ssi_types.CredentialMapper.isW3cCredential(credential)) {
if (!credential.issuer) {
credential.issuer = {
id: issuer
};
} else if (typeof credential.issuer === "object" && !credential.issuer.id) {
credential.issuer.id = issuer;
}
const subjectIsArray = Array.isArray(credential.credentialSubject);
let credentialSubjects = Array.isArray(credential.credentialSubject) ? credential.credentialSubject : [
credential.credentialSubject
];
credentialSubjects = credentialSubjects.map((subject) => {
if (!subject.id) {
subject.id = jwtVerifyResult.did;
}
return subject;
});
credential.credentialSubject = subjectIsArray ? credentialSubjects : credentialSubjects[0];
if ((0, import_ssi_sdk.contextHasPlugin)(context, "slAddStatusToCredential")) {
const credentialStatusVC = await context.agent.slAddStatusToCredential({
credential,
statusLists
});
if (credential.credentialStatus && !credential.credentialStatus.statusListCredential) {
credential.credentialStatus = credentialStatusVC.credentialStatus;
}
}
const result = await context.agent.createVerifiableCredential({
credential,
proofFormat,
removeOriginalFields: false,
fetchRemoteContexts: true,
domain: typeof credential.issuer === "object" ? credential.issuer.id : credential.issuer,
...resolution.kid && {
header: {
kid: resolution.kid
}
}
});
return proofFormat === "jwt" && "jwt" in result.proof ? result.proof.jwt : result;
} else if (import_ssi_types.CredentialMapper.isSdJwtDecodedCredentialPayload(credential)) {
const sdJwtPayload = credential;
if (sdJwtPayload.iss === void 0) {
sdJwtPayload.iss = issuer;
}
if (sdJwtPayload.iat === void 0) {
sdJwtPayload.iat = Math.floor((/* @__PURE__ */ new Date()).getTime() / 1e3);
}
let disclosureFrame;
if ("disclosureFrame" in credential) {
disclosureFrame = credential["disclosureFrame"];
delete credential["disclosureFrame"];
} else {
disclosureFrame = {
_sd: credential["_sd"]
};
}
if ((0, import_ssi_sdk.contextHasPlugin)(context, "slAddStatusToSdJwtCredential")) {
if (sdJwtPayload.status && sdJwtPayload.status.status_list || statusLists && statusLists.length > 0) {
const sdJwtPayloadWithStatus = await context.agent.slAddStatusToSdJwtCredential({
credential: sdJwtPayload,
statusLists
});
if (sdJwtPayload.status?.status_list?.idx) {
if (!sdJwtPayloadWithStatus.status || !sdJwtPayloadWithStatus.status.status_list) {
return Promise.reject(Error("slAddStatusToSdJwtCredential did not return a status_list"));
}
if (statusLists && statusLists.length > 0) {
const statusList = statusLists[0];
statusList.statusListId = sdJwtPayloadWithStatus.status.status_list.uri;
statusList.statusListIndex = sdJwtPayloadWithStatus.status.status_list.idx;
}
sdJwtPayload.status.status_list.idx = sdJwtPayloadWithStatus.status.status_list.idx;
}
}
}
const result = await context.agent.createSdJwtVc({
credentialPayload: sdJwtPayload,
disclosureFrame,
resolution
});
return result.credential;
}
return Promise.reject("VC issuance failed, an incorrect or unsupported credential was supplied");
}
__name(issueVCCallback, "issueVCCallback");
return issueVCCallback;
}
__name(getCredentialSignerCallback, "getCredentialSignerCallback");
async function createVciIssuerBuilder(args, context) {
const { issuerOpts, issuerMetadata, authorizationServerMetadata } = args;
const builder = new import_oid4vci_issuer.VcIssuerBuilder();
const resolver = args.resolver ?? args?.issuerOpts?.didOpts?.resolveOpts?.resolver ?? args.issuerOpts?.didOpts?.resolveOpts?.jwtVerifyOpts?.resolver ?? (0, import_ssi_sdk_ext.getAgentResolver)(context);
if (!resolver) {
throw Error("A Resolver is necessary to verify DID JWTs");
}
const idOpts = (0, import_ssi_sdk_ext2.legacyKeyRefsToIdentifierOpts)({
didOpts: issuerOpts.didOpts,
idOpts: issuerOpts.idOpts
});
const jwtVerifyOpts = {
...issuerOpts?.didOpts?.resolveOpts?.jwtVerifyOpts,
...args?.issuerOpts?.resolveOpts?.jwtVerifyOpts,
resolver,
audience: issuerMetadata.credential_issuer
};
builder.withIssuerMetadata(issuerMetadata);
builder.withAuthorizationMetadata(authorizationServerMetadata);
builder.withCredentialSignerCallback(await getCredentialSignerCallback(idOpts, context));
if (issuerOpts.asClientOpts) {
builder.withASClientMetadata(issuerOpts.asClientOpts);
}
builder.withJWTVerifyCallback(getJwtVerifyCallback({
verifyOpts: jwtVerifyOpts
}, context));
if (args.credentialDataSupplier) {
builder.withCredentialDataSupplier(args.credentialDataSupplier);
}
builder.withInMemoryCNonceState();
builder.withInMemoryCredentialOfferState();
builder.withInMemoryCredentialOfferURIState();
return builder;
}
__name(createVciIssuerBuilder, "createVciIssuerBuilder");
async function createVciIssuer({ issuerOpts, issuerMetadata, authorizationServerMetadata, credentialDataSupplier }, context) {
return (await createVciIssuerBuilder({
issuerOpts,
issuerMetadata,
authorizationServerMetadata,
credentialDataSupplier
}, context)).build();
}
__name(createVciIssuer, "createVciIssuer");
async function createAuthRequestUriCallback(opts) {
async function authRequestUriCallback() {
const path = opts.path.replace(":definitionId", opts.presentationDefinitionId);
return (0, import_cross_fetch.default)(path, {
method: "POST",
headers: {
"Content-Type": "application/json"
}
}).then(async (response) => {
if (response.status >= 400) {
return Promise.reject(Error(await response.text()));
} else {
const responseData = await response.json();
if (!responseData.authRequestURI) {
return Promise.reject(Error("Missing auth request uri in response body"));
}
return responseData.authRequestURI;
}
});
}
__name(authRequestUriCallback, "authRequestUriCallback");
return authRequestUriCallback;
}
__name(createAuthRequestUriCallback, "createAuthRequestUriCallback");
async function createVerifyAuthResponseCallback(opts) {
async function verifyAuthResponseCallback(correlationId) {
return (0, import_cross_fetch.default)(opts.path, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
definitionId: opts.presentationDefinitionId,
correlationId
})
}).then(async (response) => {
if (response.status >= 400) {
return Promise.reject(Error(await response.text()));
} else {
const responseData = await response.json();
if (!responseData.status) {
return Promise.reject(Error("Missing status in response body"));
}
return responseData.status === import_did_auth_siop.AuthorizationResponseStateStatus.VERIFIED;
}
});
}
__name(verifyAuthResponseCallback, "verifyAuthResponseCallback");
return verifyAuthResponseCallback;
}
__name(createVerifyAuthResponseCallback, "createVerifyAuthResponseCallback");
// src/IssuerInstance.ts
var IssuerInstance = class {
static {
__name(this, "IssuerInstance");
}
_issuer;
_metadataOptions;
_issuerOptions;
_issuerMetadata;
_authorizationServerMetadata;
constructor({ issuerOpts, metadataOpts, issuerMetadata, authorizationServerMetadata }) {
this._issuerOptions = issuerOpts;
this._metadataOptions = metadataOpts;
this._issuerMetadata = issuerMetadata;
this._authorizationServerMetadata = authorizationServerMetadata;
}
async get(opts) {
if (!this._issuer) {
const builder = await createVciIssuerBuilder({
issuerOpts: this.issuerOptions,
issuerMetadata: this.issuerMetadata,
authorizationServerMetadata: this.authorizationServerMetadata,
credentialDataSupplier: opts?.credentialDataSupplier
}, opts.context);
this._issuer = builder.build();
}
return this._issuer;
}
get issuerOptions() {
return this._issuerOptions;
}
get metadataOptions() {
return this._metadataOptions;
}
get issuerMetadata() {
return this._issuerMetadata;
}
set issuerMetadata(value) {
this._issuerMetadata = value;
}
get authorizationServerMetadata() {
return this._authorizationServerMetadata;
}
};
// src/agent/OID4VCIIssuer.ts
var OID4VCIIssuer = class _OID4VCIIssuer {
static {
__name(this, "OID4VCIIssuer");
}
static _DEFAULT_OPTS_KEY = "_default";
instances = /* @__PURE__ */ new Map();
schema = schema.IDidAuthSiopOpAuthenticator;
methods = {
oid4vciCreateOfferURI: this.oid4vciCreateOfferURI.bind(this),
oid4vciIssueCredential: this.oid4vciIssueCredential.bind(this),
oid4vciCreateAccessTokenResponse: this.oid4vciCreateAccessTokenResponse.bind(this),
oid4vciGetInstance: this.oid4vciGetInstance.bind(this)
};
_opts;
constructor(opts) {
this._opts = opts ?? {};
}
async oid4vciCreateOfferURI(createArgs, context) {
return await this.oid4vciGetInstance(createArgs, context).then((instance) => instance.get({
context
})).then((issuer) => issuer.createCredentialOfferURI(createArgs).then((response) => {
const result = response;
if (this._opts.returnSessions === false) {
delete result.session;
}
return result;
}));
}
async oid4vciIssueCredential(issueArgs, context) {
return await this.oid4vciGetInstance(issueArgs, context).then((instance) => instance.get({
context
})).then((issuer) => issuer.issueCredential(issueArgs));
}
async oid4vciCreateAccessTokenResponse(accessTokenArgs, context) {
return await this.oid4vciGetInstance(accessTokenArgs, context).then(async (instance) => {
const issuer = await instance.get({
context
});
await (0, import_oid4vci_issuer2.assertValidAccessTokenRequest)(accessTokenArgs.request, {
credentialOfferSessions: issuer.credentialOfferSessions,
expirationDuration: accessTokenArgs.expirationDuration
});
const accessTokenIssuer = instance.issuerOptions.idOpts?.issuer ?? instance.issuerOptions.didOpts?.idOpts.identifier.toString();
if (!accessTokenIssuer) {
return Promise.reject(Error(`Could not determine access token issuer`));
}
return (0, import_oid4vci_issuer2.createAccessTokenResponse)(accessTokenArgs.request, {
accessTokenIssuer,
tokenExpiresIn: accessTokenArgs.expirationDuration,
cNonceExpiresIn: accessTokenArgs.expirationDuration,
cNonces: issuer.cNonces,
credentialOfferSessions: issuer.credentialOfferSessions,
accessTokenSignerCallback: await getAccessTokenSignerCallback(instance.issuerOptions, context)
});
});
}
getExternalAS(issuerMetadata) {
if ("authorization_servers" in issuerMetadata && Array.isArray(issuerMetadata.authorization_servers)) {
return issuerMetadata.authorization_servers.find((as) => as !== issuerMetadata.credential_issuer);
}
return void 0;
}
async createIssuerInstance(args, context) {
const credentialIssuer = args.credentialIssuer ?? _OID4VCIIssuer._DEFAULT_OPTS_KEY;
const metadataOpts = await this.getMetadataOpts({
...args,
credentialIssuer
}, context);
const issuerMetadata = await this.getIssuerMetadata({
...args,
credentialIssuer
}, context);
const externalAS = this.getExternalAS(issuerMetadata);
let asMetadataResponse = void 0;
if (externalAS) {
asMetadataResponse = await (0, import_oid4vci_client.retrieveWellknown)(externalAS, import_oid4vci_common.WellKnownEndpoints.OPENID_CONFIGURATION, {
errorOnNotFound: false
});
if (!asMetadataResponse) {
asMetadataResponse = await (0, import_oid4vci_client.retrieveWellknown)(externalAS, import_oid4vci_common.WellKnownEndpoints.OAUTH_AS, {
errorOnNotFound: true
});
}
}
const authorizationServerMetadata = asMetadataResponse?.successBody ? asMetadataResponse.successBody : await this.getAuthorizationServerMetadataFromStore({
...args,
credentialIssuer
}, context);
const issuerOpts = await this.getIssuerOptsFromStore({
...args,
credentialIssuer
}, context);
if (!issuerOpts.resolveOpts) {
issuerOpts.resolveOpts = {
...issuerOpts.didOpts?.resolveOpts,
...this._opts.resolveOpts
};
}
if (!issuerOpts.resolveOpts?.resolver) {
issuerOpts.resolveOpts.resolver = (0, import_ssi_sdk_ext3.getAgentResolver)(context);
}
this.instances.set(credentialIssuer, new IssuerInstance({
issuerOpts,
metadataOpts,
issuerMetadata,
authorizationServerMetadata
}));
return this.oid4vciGetInstance(args, context);
}
async oid4vciGetInstance(args, context) {
const credentialIssuer = args.credentialIssuer ?? _OID4VCIIssuer._DEFAULT_OPTS_KEY;
if (!this.instances.has(credentialIssuer)) {
await this.createIssuerInstance(args, context);
}
return this.instances.get(credentialIssuer);
}
async getIssuerOptsFromStore(opts, context) {
const credentialIssuer = opts.credentialIssuer;
const storeId = await this.storeId(opts, context);
const namespace = await this.namespace(opts, context);
const options = await context.agent.oid4vciStoreGetIssuerOpts({
metadataType: "issuer",
correlationId: credentialIssuer,
storeId,
namespace
});
if (!options) {
throw Error(`Could not get specific nor default options for definition ${credentialIssuer}`);
}
return options;
}
async getMetadataOpts(opts, context) {
const credentialIssuer = opts.credentialIssuer;
const storeId = await this.storeId(opts, context);
const storeNamespace = await this.namespace(opts, context);
return {
credentialIssuer,
storeId,
storeNamespace
};
}
async getIssuerMetadata(opts, context) {
const metadataOpts = await this.getMetadataOpts(opts, context);
const metadata = await context.agent.oid4vciStoreGetMetadata({
metadataType: "issuer",
correlationId: metadataOpts.credentialIssuer,
namespace: metadataOpts.storeNamespace,
storeId: metadataOpts.storeId
});
if (!metadata) {
throw Error(`Issuer metadata not found for issuer ${opts.credentialIssuer}, namespace ${opts.namespace} and store ${opts.storeId}`);
}
return metadata;
}
async getAuthorizationServerMetadataFromStore(opts, context) {
const metadataOpts = await this.getMetadataOpts(opts, context);
const metadata = await context.agent.oid4vciStoreGetMetadata({
metadataType: "authorizationServer",
correlationId: metadataOpts.credentialIssuer,
namespace: metadataOpts.storeNamespace,
storeId: metadataOpts.storeId
});
if (!metadata) {
throw Error(`Authorization server ${opts.credentialIssuer} metadata not found for namespace ${metadataOpts.storeNamespace} and store ${metadataOpts.storeId}`);
}
return metadata;
}
async storeId(opts, context) {
const storeId = opts?.storeId ?? this._opts?.defaultStoreId ?? await context?.agent.oid4vciStoreDefaultStoreId();
if (!storeId) {
throw Error("Please provide a store id a default value, or provide the context for a global default store id");
}
return storeId;
}
async namespace(opts, context) {
const namespace = opts?.namespace ?? this._opts?.defaultNamespace ?? await context?.agent.oid4vciStoreDefaultNamespace();
if (!namespace) {
throw Error("Please provide a namespace a default value, or provide the context for a global default namespace");
}
return namespace;
}
};
// src/index.ts
var schema = require_plugin_schema();
//# sourceMappingURL=index.cjs.map