From 1144fe753ad70ba811c677f91277ae80c764cedb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafa=C5=82=20Leszko?= Date: Fri, 3 Feb 2023 17:23:20 +0100 Subject: [PATCH] Add options for passing client's credentials with env variables --- lib.js | 36 ++++++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/lib.js b/lib.js index a82271e..1c2083d 100644 --- a/lib.js +++ b/lib.js @@ -6,9 +6,11 @@ import { connect } from '@ucanto/client' import * as CAR from '@ucanto/transport/car' import * as CBOR from '@ucanto/transport/cbor' import * as HTTP from '@ucanto/transport/http' +import { derive } from "@ucanto/principal/ed25519"; import { parse } from '@ipld/dag-ucan/did' -import { create } from '@web3-storage/w3up-client' +import { Client, create } from '@web3-storage/w3up-client' import { StoreConf } from '@web3-storage/access/stores/store-conf' +import { AgentData } from "@web3-storage/access"; import { CarReader } from '@ipld/car' /** @@ -42,8 +44,14 @@ export function filesize (bytes) { * Get a new API client configured from env vars. */ export function getClient () { + if (process.env.W3_PRINCIPAL_KEY && process.env.W3_DELEGATION_PROOF) { + // use credentials from env variables + return createFromStatic(process.env.W3_PRINCIPAL_KEY, process.env.W3_DELEGATION_PROOF) + } + + // use stored credentials const store = new StoreConf({ profile: process.env.W3_STORE_NAME ?? 'w3cli' }) - + let serviceConf if ( process.env.W3_ACCESS_SERVICE_DID && @@ -193,3 +201,27 @@ async function * filesFromDir (dir, filter) { } } } + +async function createFromStatic(principalKey, delegationProof) { + // create a client with the UCAN private key + const principal = await derive( + Buffer.from(principalKey, "base64") + ); + const data = await AgentData.create({ principal }); + const client = new Client(data); + + // create a space with the delegation proof + const blocks = []; + const reader = await CarReader.fromBytes( + Buffer.from(delegationProof, "base64") + ); + for await (const block of reader.blocks()) { + blocks.push(block); + } + const proof = importDAG(blocks); + + const space = await client.addSpace(proof); + await client.setCurrentSpace(space.did()); + + return client; +}