-
Notifications
You must be signed in to change notification settings - Fork 1
Add VC API interaction support. #61
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 16 commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
ed5012b
Start implementing optional `interactions` feature.
dlongley 4dba281
Add route for getting interaction exchange state.
dlongley ed292b3
Move zcap client into its own file.
dlongley 8b82d5b
Move interactions routes to their own file.
dlongley de6a522
Return early when interactions not enabled.
dlongley 815666a
Limit per exchange polling via LRU cache.
dlongley cdf27f7
Start adding interaction tests.
dlongley 8fc0a1c
Fix typo in test assertion.
dlongley aff0596
Add FIXME.
dlongley e4b11ef
Integrate interactions with `@bedrock/notify`.
dlongley 067e637
Refactor interactions to use "interaction types" terminology.
dlongley b50cbac
Add push notification callbacks to interaction processing.
dlongley ae7cb67
Refactor tests.
dlongley 9f152d2
Make interactions config reprocessable for testing purposes.
dlongley a6e1f9c
Add vc-workflow instance for testing interactions.
dlongley c82b74e
Add, improve, and pass interaction tests.
dlongley b9988ec
Update copyright header dates.
dlongley File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,246 @@ | ||
/*! | ||
* Copyright (c) 2020-2025 Digital Bazaar, Inc. All rights reserved. | ||
*/ | ||
import * as bedrock from '@bedrock/core'; | ||
import * as schemas from '../schemas/bedrock-profile-http.js'; | ||
import {poll, pollers, push} from '@bedrock/notify'; | ||
import {agent} from '@bedrock/https-agent'; | ||
import {asyncHandler} from '@bedrock/express'; | ||
import {ensureAuthenticated} from '@bedrock/passport'; | ||
import {httpClient} from '@digitalbazaar/http-client'; | ||
import {createValidateMiddleware as validate} from '@bedrock/validation'; | ||
import {ZCAP_CLIENT as zcapClient} from './zcapClient.js'; | ||
|
||
const {config, util: {BedrockError}} = bedrock; | ||
|
||
let DEFINITIONS_BY_TYPE_MAP; | ||
let DEFINITIONS_BY_ID_MAP; | ||
|
||
// use a TTL of 1 second to account for the case where a push notification | ||
// isn't received by the same instance that the client hits, but prevent | ||
// requests from triggering a hit to the workflow service backend more | ||
// frequently than 1 second | ||
const POLL_TTL = 1000; | ||
|
||
bedrock.events.on('bedrock.init', () => { | ||
processInteractionConfig(); | ||
}); | ||
|
||
bedrock.events.on('bedrock-express.configure.routes', app => { | ||
const interactionsPath = '/interactions'; | ||
const routes = { | ||
interactions: interactionsPath, | ||
interaction: `${interactionsPath}/:localInteractionId/:localExchangeId`, | ||
callback: `${interactionsPath}/:localInteractionId/callbacks/:pushToken` | ||
}; | ||
|
||
// base URL for server | ||
const {baseUri} = bedrock.config.server; | ||
|
||
// create an interaction to exchange VCs | ||
app.post( | ||
routes.interactions, | ||
ensureAuthenticated, | ||
validate({bodySchema: schemas.createInteraction}), | ||
asyncHandler(async (req, res) => { | ||
const {id: accountId} = req.user.account || {}; | ||
const {type, exchange: {variables}} = req.body; | ||
|
||
const definition = DEFINITIONS_BY_TYPE_MAP?.get(type); | ||
if(!definition) { | ||
throw new BedrockError(`Interaction type "${type}" not found.`, { | ||
name: 'NotFoundError', | ||
details: { | ||
httpStatusCode: 404, | ||
public: true | ||
} | ||
}); | ||
} | ||
|
||
// create a push token | ||
const {token} = await push.createPushToken({event: 'exchangeUpdated'}); | ||
|
||
// compute callback URL | ||
const {localInteractionId} = definition; | ||
const pushCallbackUrl = | ||
`${baseUri}${interactionsPath}/${localInteractionId}` + | ||
`/callbacks/${token}`; | ||
|
||
// create exchange with given variables | ||
const exchange = { | ||
// FIXME: use `expires` instead of now-deprecated `ttl` | ||
// 15 minute expiry in seconds | ||
ttl: 60 * 15, | ||
// template variables | ||
variables: { | ||
...variables, | ||
pushCallbackUrl, | ||
accountId | ||
} | ||
}; | ||
const capability = definition.zcaps.get('readWriteExchanges'); | ||
const response = await zcapClient.write({json: exchange, capability}); | ||
const exchangeId = response.headers.get('location'); | ||
// reuse `localExchangeId` in path | ||
const localExchangeId = exchangeId.slice(exchangeId.lastIndexOf('/') + 1); | ||
const id = `${config.server.baseUri}${routes.interactions}/` + | ||
`${localInteractionId}/${localExchangeId}`; | ||
res.json({interactionId: id, exchangeId}); | ||
})); | ||
|
||
// gets an interaction | ||
app.get( | ||
routes.interaction, | ||
ensureAuthenticated, | ||
validate({querySchema: schemas.getInteractionQuery}), | ||
asyncHandler(async (req, res) => { | ||
const {id: accountId} = req.user.account || {}; | ||
const { | ||
params: {localInteractionId, localExchangeId}, | ||
query: {iuv} | ||
} = req; | ||
|
||
// get interaction definition | ||
const definition = _getInteractionDefinition({localInteractionId}); | ||
|
||
// determine full exchange ID based on related capability | ||
const capability = definition.zcaps.get('readWriteExchanges'); | ||
const exchangeId = `${capability.invocationTarget}/${localExchangeId}`; | ||
|
||
// if an "Interaction URL Version" is present send "protocols" | ||
// (note: validation requires it to be `1`, so no need to check its value) | ||
if(iuv) { | ||
// FIXME: send to a QR-code page if supported | ||
// FIXME: check config for supported QR code route and use it | ||
// instead of hard-coded value | ||
if(req.accepts('html') || !req.accepts('json')) { | ||
return res.redirect(`${req.originalUrl}/qr-code`); | ||
} | ||
try { | ||
const url = `${exchangeId}/protocols`; | ||
const {data: protocols} = await httpClient.get(url, {agent}); | ||
res.json(protocols); | ||
} catch(cause) { | ||
throw new BedrockError( | ||
'Unable to serve protocols object: ' + cause.message, { | ||
name: 'OperationError', | ||
details: {httpStatusCode: 500, public: true}, | ||
cause | ||
}); | ||
} | ||
} | ||
|
||
// poll the exchange... | ||
const result = await poll({ | ||
id: exchangeId, | ||
poller: _createExchangePoller({accountId, capability}), | ||
ttl: POLL_TTL | ||
}); | ||
|
||
res.json(result.value); | ||
})); | ||
|
||
// push event handler | ||
app.post( | ||
routes.callback, | ||
push.createVerifyPushTokenMiddleware({event: 'exchangeUpdated'}), | ||
asyncHandler(async (req, res) => { | ||
const {event: {data: {exchangeId: id}}} = req.body; | ||
const {localInteractionId} = req.params; | ||
|
||
// get interaction definition | ||
const definition = _getInteractionDefinition({localInteractionId}); | ||
|
||
// get capability for fetching exchange and verify its invocation target | ||
// matches the exchange ID passed | ||
const capability = definition.zcaps.get('readWriteExchanges'); | ||
if(!id.startsWith(capability.invocationTarget)) { | ||
throw new BedrockError('Not authorized.', { | ||
name: 'NotAllowedError', | ||
details: {httpStatusCode: 403, public: true} | ||
}); | ||
} | ||
|
||
// poll (and clear cache) | ||
await poll({ | ||
id, | ||
poller: _createExchangePoller({capability}), | ||
ttl: POLL_TTL, | ||
useCache: false | ||
}); | ||
res.sendStatus(204); | ||
})); | ||
}); | ||
|
||
export function processInteractionConfig() { | ||
const cfg = config['profile-http']; | ||
|
||
// interactions feature is optional, return early if not enabled | ||
if(!cfg.interactions?.enabled) { | ||
return; | ||
} | ||
|
||
// parse interaction types when enabled | ||
const {types = {}} = cfg.interactions; | ||
DEFINITIONS_BY_TYPE_MAP = new Map(); | ||
DEFINITIONS_BY_ID_MAP = new Map(); | ||
for(const typeName in types) { | ||
const {localInteractionId, zcaps} = types[typeName]; | ||
if(!localInteractionId) { | ||
throw new TypeError( | ||
'"bedrock.config.profile-http.interaction.types" must each ' + | ||
'have "localInteractionId".'); | ||
} | ||
const definition = { | ||
name: typeName, | ||
localInteractionId, | ||
zcaps: new Map() | ||
}; | ||
for(const zcapName in zcaps) { | ||
const zcap = zcaps[zcapName]; | ||
definition.zcaps.set(zcapName, JSON.parse(zcap)); | ||
} | ||
if(!definition.zcaps.has('readWriteExchanges')) { | ||
throw new TypeError( | ||
'"bedrock.config.profile-http.interaction.types" must each ' + | ||
'have "zcaps.readWriteExchanges".'); | ||
} | ||
DEFINITIONS_BY_TYPE_MAP.set(typeName, definition); | ||
DEFINITIONS_BY_ID_MAP.set(localInteractionId, definition); | ||
} | ||
} | ||
|
||
function _createExchangePoller({accountId, capability}) { | ||
return pollers.createExchangePoller({ | ||
zcapClient, | ||
capability, | ||
filterExchange({exchange/*, previousPollResult*/}) { | ||
// if `accountId` given, ensure it matches exchange variables | ||
if(accountId && exchange?.variables.accountId !== accountId) { | ||
throw new BedrockError('Not authorized.', { | ||
name: 'NotAllowedError', | ||
details: {httpStatusCode: 403, public: true} | ||
}); | ||
} | ||
// return only information that should be accessible to client | ||
return { | ||
exchange: { | ||
state: exchange.state, | ||
result: exchange.variables.results?.finish | ||
} | ||
}; | ||
} | ||
}); | ||
} | ||
|
||
function _getInteractionDefinition({localInteractionId}) { | ||
const definition = DEFINITIONS_BY_ID_MAP?.get(localInteractionId); | ||
if(!definition) { | ||
throw new BedrockError( | ||
`Interaction type for "${localInteractionId}" not found.`, { | ||
name: 'NotFoundError', | ||
details: {httpStatusCode: 404, public: true} | ||
}); | ||
} | ||
return definition; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
/*! | ||
* Copyright (c) 2020-2024 Digital Bazaar, Inc. All rights reserved. | ||
dlongley marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
*/ | ||
import * as bedrock from '@bedrock/core'; | ||
import {Ed25519Signature2020} from '@digitalbazaar/ed25519-signature-2020'; | ||
import {getAppIdentity} from '@bedrock/app-identity'; | ||
import {httpsAgent} from '@bedrock/https-agent'; | ||
import {ZcapClient} from '@digitalbazaar/ezcap'; | ||
|
||
export let ZCAP_CLIENT; | ||
|
||
bedrock.events.on('bedrock.init', () => { | ||
// create signer using the application's capability invocation key | ||
const {keys: {capabilityInvocationKey}} = getAppIdentity(); | ||
|
||
ZCAP_CLIENT = new ZcapClient({ | ||
agent: httpsAgent, | ||
invocationSigner: capabilityInvocationKey.signer(), | ||
SuiteClass: Ed25519Signature2020 | ||
}); | ||
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.