From 59e5eb5d58190c1e60566c6857a0c99db7d6f25b Mon Sep 17 00:00:00 2001 From: Denis Carriere Date: Tue, 31 Jan 2023 21:45:59 -0500 Subject: [PATCH] Add authentication_token --- example.js | 2 +- examples/subtivity.ts | 2 +- src/index.ts | 6 ++++-- src/utils.ts | 22 ++++++++++++++++++++++ 4 files changed, 28 insertions(+), 4 deletions(-) diff --git a/example.js b/example.js index e0c52f0..701992a 100644 --- a/example.js +++ b/example.js @@ -10,7 +10,7 @@ const stopBlockNum = "+10"; const substreams = new Substreams(outputModule, { startBlockNum, stopBlockNum, - authorization: process.env.SUBSTREAMS_API_TOKEN + authorization: "" }); (async () => { diff --git a/examples/subtivity.ts b/examples/subtivity.ts index 5dc0417..3c8a0cb 100644 --- a/examples/subtivity.ts +++ b/examples/subtivity.ts @@ -10,7 +10,7 @@ const stopBlockNum = "+10"; const substreams = new Substreams(outputModule, { startBlockNum, stopBlockNum, - authorization: process.env.SUBSTREAMS_API_TOKEN + authorization: process.env.STREAMINGFAST_KEY }); (async () => { diff --git a/src/index.ts b/src/index.ts index 9870fd2..eeb31e8 100644 --- a/src/index.ts +++ b/src/index.ts @@ -20,7 +20,7 @@ export * from "./generated/sf/substreams/v1/substreams" export * from "./utils"; // Utils -import { parseBlockData, parseStopBlock } from './utils'; +import { parseAuthorization, parseBlockData, parseStopBlock } from './utils'; interface MapOutput extends ModuleOutput { data: { @@ -88,7 +88,9 @@ export class Substreams extends (EventEmitter as new () => TypedEmitter { + metadata.add('authorization', token); + }) const creds = credentials.combineChannelCredentials( credentials.createSsl(), credentials.createFromMetadataGenerator((_, callback) => callback(null, metadata)), diff --git a/src/utils.ts b/src/utils.ts index 393537b..18ef8c5 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -29,6 +29,28 @@ export function getSeconds( clock?: Clock ) { return Number(clock?.timestamp?.seconds); } +interface Token { + token: string; + expires_at: number; +} + +export async function authentication_token(api_key: string) { + const url = 'https://auth.streamingfast.io/v1/auth/issue'; + const response = await fetch(url, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({api_key}) + }) + return response.json() as Promise; +} + +export async function parseAuthorization(authorization: string ) { + if ( authorization.includes("server_") ) { + return (await authentication_token(authorization)).token; + } + return authorization; +} + export const isIpfs = ( str: string ) => /^Qm[1-9A-Za-z]{44}$/.test(str); export function parseStopBlock( startBlock: string, stopBlock?: string ) {