{"version":3,"file":"cd.cjs","sources":["../../../src/rdf-and-cd/cd.js"],"sourcesContent":["// Claim deduction from verifiable presentations.\n\nimport deepEqual from 'deep-equal';\nimport jsonld from 'jsonld';\nimport { validate, prove, infer } from 'rify';\nimport { assert } from '../utils/assert';\nimport { expandedCredentialProperty } from '../vc/constants';\nimport { fromJsonldjsCg, merge } from './claimgraph';\nimport {\n  canonRules,\n  canonProof,\n  canonClaimGraph,\n  decanonClaimGraph,\n  decanonProof,\n} from './canonicalize';\nimport { assertValidNode, assertType } from './common';\n\nexport const expandedLogicProperty = 'https://www.dock.io/rdf2020#logicV1';\nexport const expandedProofProperty = 'https://w3id.org/security#proof';\nexport const expandedIssuerProperty = 'https://www.w3.org/2018/credentials#issuer';\n\n/**\n * Returns a list of all RDF statements proven by the presentation. DOES NOT VERIFY THE\n * PRESENTATION. Verification must be performed for the results of this function to be trustworthy.\n * The return value may contaim duplicate claims.\n *\n * This function throws an error if:\n * a provided proof is not applicable given the ruleset,\n * a provided proof makes unverified assumptions,\n * a provided proof is malformed.\n *\n * @param expandedPresentation - a VCDM presentation as expanded json-ld\n * @param rules - ordered list of axioms which will be accepted within proofs of composite claims\n * @returns {Promise<Object[]>}\n */\nexport async function acceptCompositeClaims(expandedPresentation, rules) {\n  assert(\n    rules !== undefined,\n    'An axiom list must be provided. Hint: rules may be \"[]\" to reject all.',\n  );\n\n  const cg = await presentationToEEClaimGraph(expandedPresentation);\n  const proof = extractProof(expandedPresentation);\n  const implied = getImplications(cg, proof, rules);\n\n  // return (claimgraph U implied)\n  return [...cg, ...implied];\n}\n\n/**\n * Convert a list of expanded credentials which have already been verified into an RDF claim graph.\n * The resulting claimgraph is in Explicit Ethos form.\n *\n * @param expandedCredentials - A list of expanded credentials, each is expected to be a separate\n *                              @graph.\n * @returns {Promise<Object[]>}\n */\nasync function credsToEEClaimGraph(expandedCredentials) {\n  const ees = await Promise.all(expandedCredentials.map(credToEECG));\n  return merge(ees);\n}\n\n/**\n * Convert a single expanded credential which has already been verified into an RDF claim graph.\n *\n * @returns {Promise<Object[]>}\n */\nasync function credToEECG(expandedCredential) {\n  assert(\n    expandedCredential['@graph'] !== undefined,\n    'Expected each credential to expand to its own @graph',\n  );\n  const cred = { ...unwrapE(expandedCredential['@graph']) };\n\n  // This line relies on the assumption that if the credential passed verification then the\n  // issuer property was not forged.\n  assert(\n    cred[expandedIssuerProperty] !== undefined,\n    'encountered credential without an issuer',\n  );\n  const issuer = cred[expandedIssuerProperty][0]['@id'];\n  assertType(issuer, 'string');\n  assert(!issuer.startsWith('_:'), 'issuer is assumed not to be a blank node');\n\n  // remove the proof\n  delete cred[expandedProofProperty];\n\n  // convert to claimgraph\n  const cg = fromJsonldjsCg(await jsonld.toRDF(cred));\n\n  for (const claim of cg) {\n    // Credentials containing a \"@graph\" declaration will cause an assertion error here.\n    // And rightfully so. Here's why:\n    // Each statement in a cred is passed to the reasoner as a quad with `issuer` as the graph.\n    // It would be potentially incorrect to overwrite a non-default graph.\n    // Leaving a non-default graph as-is would be unsafe.\n    // While it would be valid to simply delete quads with non-default graphs, it would be confusing\n    // to users if the content of their credential was swallowed without warning.\n    assert(\n      deepEqual(claim[3], { DefaultGraph: true }),\n      'subgraph found in credential',\n    );\n    claim[3] = { Iri: issuer };\n  }\n\n  return cg;\n}\n\n/**\n * Returns a list of all RDF statements in the presentation. DOES NOT VERIFY THE\n * PRESENTATION. Verification must be performed for the results of this function to be trustworthy.\n *\n * @param expandedPresentation - a VCDM presentation as expanded json-ld\n * @returns {Promise<Object[]>}\n */\nexport async function presentationToEEClaimGraph(expandedPresentation) {\n  const ep = unwrapE(expandedPresentation);\n\n  // get ordered list of all credentials\n  const creds = jsonld.getValues(ep, expandedCredentialProperty);\n\n  // convert them to a single claimgraph\n  return credsToEEClaimGraph(creds);\n}\n\nexport class UnverifiedAssumption extends Error {\n  constructor(unverifiedAssumption) {\n    super('Proof relies on assumption that are not in the input.');\n    this.unverifiedAssumption = unverifiedAssumption;\n  }\n}\n\n/**\n * Extracts any included proofs of composite claims from a presentation.\n * The presentation must be in expanded form.\n * Returns the proofs, concatenated together.\n *\n * @param expandedPresentation - a VCDM presentation as expanded json-ld\n * @returns {Promise<Object[]>}\n */\nexport function extractProof(expandedPresentation) {\n  return jsonld\n    .getValues(unwrapE(expandedPresentation), expandedLogicProperty)\n    .map(fromJSONLiteral)\n    .flat(1);\n}\n\n/**\n * Given a claimgraph of true assumptions, and the allowed logical rules, return the claims that are\n * proven true by proof. If the proof is not applicable given the ruleset, or makes unverified\n * assumptions, throw an error. The return value may contain duplicate claims.\n *\n * @param claimgraph - known true assumptions (usually extracted from a presentation or a cred)\n * @param proof - proof of composite claims (usually comes from calling proveh())\n * @param rules - ordered list of axioms\n * @returns {Object[]}\n */\nexport function getImplications(claimgraph, proof, rules) {\n  const valid = validateh(rules, proof);\n\n  // Check that all assumptions made by the proof were provided in the claimgraph of assumptions\n  for (const assumption of valid.assumed) {\n    if (!claimgraph.some((claim) => claimEq(claim, assumption))) {\n      throw new UnverifiedAssumption([...assumption]);\n    }\n  }\n\n  return valid.implied;\n}\n\n/**\n * Given the assumptions encoded in the provided presentation, prove a list of composite claims.\n * T return proof of composite claims as a jsonld json literal which can be attached directly to a\n * presentation as {expandedLogicProperty} before [signing and ]submitting.\n *\n * This function throws an error if the requested composite claims are unprovable.\n *\n * @param expandedPresentation - a VCDM presentation as expanded json-ld\n * @param compositeClaims - claims to prove, provide in claimgraph format\n * @param rules - ordered list of axioms which will be accepted within proofs of composite claims\n * @returns {Promise<Object>} - proof is returned as a json literal\n */\nexport async function proveCompositeClaims(\n  expandedPresentation,\n  compositeClaims,\n  rules,\n) {\n  assert(\n    rules !== undefined,\n    'An axiom list must be provided. Hint: rules may be \"[]\" to reject all.',\n  );\n  const cg = await presentationToEEClaimGraph(expandedPresentation);\n  const prevProof = await extractProof(expandedPresentation);\n  const newProof = proveh(cg, compositeClaims, rules);\n  return toJsonLiteral(prevProof.concat(newProof));\n}\n\n// prove-high\n// A higher level wrapper around prove that first converts rules, composite claims, and premises to\n// the canonical representation as defined by `canon()` in `claimgraph.js`. This wrapper\n// deserializes the returned values before passing them back to the caller.\nexport function proveh(premises, toProve, rules) {\n  foreachQuadInRules(rules, assertQuad);\n  premises.forEach(assertQuad);\n  toProve.forEach(assertQuad);\n  const proof = prove(\n    canonClaimGraph(premises),\n    canonClaimGraph(toProve),\n    canonRules(rules),\n  );\n  return decanonProof(proof);\n}\n\n// validate-high\n// A higher level wrapper around validate that first converts rules and proof to the canonical\n// representation as defined by `canon()` in `claimgraph.js`. This wrapper deserializes the\n// returned values before passing them back to the caller.\nexport function validateh(rules, proof) {\n  foreachQuadInRules(rules, assertQuad);\n  const { assumed, implied } = validate(canonRules(rules), canonProof(proof));\n  return {\n    assumed: decanonClaimGraph(assumed),\n    implied: decanonClaimGraph(implied),\n  };\n}\n\n// infer-high\n// A higher level wrapper around infer that first converts premises and rules to the canonical\n// representation as defined by `canon()` in `claimgraph.js`. This wrapper deserializes the\n// returned values before passing them back to the caller.\nexport function inferh(premises, rules) {\n  premises.forEach(assertQuad);\n  foreachQuadInRules(rules, assertQuad);\n  const inferred = infer(canonClaimGraph(premises), canonRules(rules));\n  return decanonClaimGraph(inferred);\n}\n\nfunction foreachQuadInRules(rules, f) {\n  for (const rule of rules) {\n    for (const quad of rule.if_all) {\n      f(quad);\n    }\n    for (const quad of rule.then) {\n      f(quad);\n    }\n  }\n}\n\nfunction assertQuad(quad) {\n  assert(\n    quad.length === 4,\n    () => `Quads must have length 4, got: ${JSON.stringify(quad)}`,\n  );\n}\n\n/// check two claims for equality\nfunction claimEq(a, b) {\n  for (const claim of [a, b]) {\n    if (!(claim instanceof Array) || claim.length !== 4) {\n      throw new TypeError();\n    }\n    for (const node of claim) {\n      assertValidNode(node);\n    }\n  }\n  return deepEqual(a, b);\n}\n\n// https://w3c.github.io/json-ld-syntax/#json-literals\nfunction fromJSONLiteral(literal) {\n  if (literal['@type'] !== '@json') {\n    throw new TypeError(`not a json literal: ${literal}`);\n  }\n  if (literal['@value'] === undefined) {\n    throw new TypeError(`json literal has no \"@value\": ${literal}`);\n  }\n  return literal['@value'];\n}\n\n// https://w3c.github.io/json-ld-syntax/#json-literals\nfunction toJsonLiteral(json) {\n  return {\n    '@type': '@json',\n    '@value': JSON.parse(JSON.stringify(json)),\n  };\n}\n\n// Unwrap Expanded jsonld\n//\n// jsonld expansion by jsonld-js results in an array. This module operates on expanded jsonld so\n// getting the first and only element from that expanded array is a common task.\n//\n// We assume that a root level expanded jsonld object will always be an array with exactly one\n// element.\nfunction unwrapE(expanded) {\n  assert(\n    Array.isArray(expanded) && expanded.length === 1,\n    'expected expanded jsonld as an array of one element',\n  );\n  return expanded[0];\n}\n"],"names":["assert","merge","assertType","fromJsonldjsCg","jsonld","deepEqual","expandedCredentialProperty","prove","canonClaimGraph","canonRules","decanonProof","validate","canonProof","decanonClaimGraph","infer","assertValidNode"],"mappings":";;;;;;;;;;;;;;;;AAAA;;;AAiBY,MAAC,qBAAqB,GAAG;AACzB,MAAC,qBAAqB,GAAG;AACzB,MAAC,sBAAsB,GAAG;;AAEtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,eAAe,qBAAqB,CAAC,oBAAoB,EAAE,KAAK,EAAE;AACzE,EAAEA,YAAM;AACR,IAAI,KAAK,KAAK,SAAS;AACvB,IAAI,wEAAwE;AAC5E,GAAG;;AAEH,EAAE,MAAM,EAAE,GAAG,MAAM,0BAA0B,CAAC,oBAAoB,CAAC;AACnE,EAAE,MAAM,KAAK,GAAG,YAAY,CAAC,oBAAoB,CAAC;AAClD,EAAE,MAAM,OAAO,GAAG,eAAe,CAAC,EAAE,EAAE,KAAK,EAAE,KAAK,CAAC;;AAEnD;AACA,EAAE,OAAO,CAAC,GAAG,EAAE,EAAE,GAAG,OAAO,CAAC;AAC5B;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,mBAAmB,CAAC,mBAAmB,EAAE;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