From ea47bc9dea6c17d40ff2443c7969856ea10aa77e Mon Sep 17 00:00:00 2001 From: Hugo Dias Date: Thu, 3 Mar 2022 13:00:12 +0000 Subject: [PATCH] feat: service validation --- src/service.js | 27 ++++++++++++++++++++------- src/ucan-chain.js | 9 ++++----- 2 files changed, 24 insertions(+), 12 deletions(-) diff --git a/src/service.js b/src/service.js index 2ff2959..e21fcac 100644 --- a/src/service.js +++ b/src/service.js @@ -1,6 +1,7 @@ import * as ucan from './ucan-storage.js' import { UcanChain } from './ucan-chain.js' import { KeyPair } from './keypair.js' +import { storageSemantics } from './semantics.js' export class Service { /** @@ -23,24 +24,36 @@ export class Service { } /** + * Validates UCAN for capability + * * @param {string} encodedUcan - * @param {import('./types').ValidateOptions} options + * @param {import('./types.js').Capability} capability + * @returns {Promise} Returns the root ucan for capability */ - async validate(encodedUcan, options) { - const token = await UcanChain.fromToken(encodedUcan, options) + async validate(encodedUcan, capability) { + const token = await UcanChain.fromToken(encodedUcan, {}) if (token.audience() !== this.did()) { throw new Error('Invalid UCAN: Audience does not match this service.') } - return token + const origin = token.claim(capability, storageSemantics) + + if (origin.issuer() !== this.did()) { + throw new Error('Invalid UCAN: Root issuer does not match this service.') + } + + return origin } /** - * @param {UcanChain} ucan + * @param {string} encodedUcan */ - static caps(ucan) { - // return ucans.capabilities(ucan, storageSemantics) + async validateFromCaps(encodedUcan) { + const token = await UcanChain.fromToken(encodedUcan, {}) + const caps = token.caps(storageSemantics) + + return caps[0] } did() { diff --git a/src/ucan-chain.js b/src/ucan-chain.js index 937a394..bfbf7b6 100644 --- a/src/ucan-chain.js +++ b/src/ucan-chain.js @@ -5,7 +5,7 @@ import * as ucan from './index.js' * @param {import('./types').CapabilitySemantics} semantics * @param {UcanChain} ucan */ -function* findValidCaps(semantics, ucan) { +export function* findValidCaps(semantics, ucan) { const caps = ucan.capabilities() const parentCaps = [] @@ -73,7 +73,7 @@ function canDelegate(ucan, capParsed, semantics) { * @param {UcanChain} ucan * @param {A} capParsed * @param {import('./types').CapabilitySemantics} semantics - * @returns {UcanChain | undefined} + * @returns {UcanChain} */ function findRoot(ucan, capParsed, semantics) { const proofs = ucan.proofs() @@ -158,9 +158,8 @@ export class UcanChain { const validCaps = [] for (const cap of findValidCaps(semantics, this)) { try { - if (findRoot(this, cap, semantics)) { - validCaps.push(cap) - } + const root = findRoot(this, cap, semantics) + validCaps.push({ root, cap }) } catch {} }