1
- import { Store } from '.' ;
2
- import { Commit , serializeDeterministically } from './commit' ;
1
+ import { getTimestampNow , Store } from '.' ;
2
+ import { Commit , serializeDeterministically , signToBase64 } from './commit' ;
3
3
import { parseJsonADResource } from './parse' ;
4
4
import { Resource } from './resource' ;
5
+ import { Agent } from '@tomic/lib' ;
5
6
6
7
/**
7
8
* Fetches and Parses a Resource. Can fetch through another atomic server if you
@@ -26,6 +27,10 @@ export async function fetchResource(
26
27
tryValidURL ( subject ) ;
27
28
const requestHeaders : HeadersInit = new Headers ( ) ;
28
29
requestHeaders . set ( 'Accept' , 'application/ad+json' ) ;
30
+ // Sign the request if there is an agent present
31
+ store &&
32
+ store . getAgent ( ) &&
33
+ ( await signRequest ( subject , store . getAgent ( ) , requestHeaders ) ) ;
29
34
let url = subject ;
30
35
if ( from !== undefined ) {
31
36
const newURL = new URL ( `${ from } /path` ) ;
@@ -116,3 +121,17 @@ export function removeQueryParamsFromURL(subject: string): string {
116
121
// return subject.split('?')[0];
117
122
return subject ;
118
123
}
124
+
125
+ /** Creates an x-atomic-signature header */
126
+ async function signRequest (
127
+ /** The resource meant to be fetched */
128
+ subject : string ,
129
+ agent : Agent ,
130
+ headers : Headers ,
131
+ ) : Promise < Headers > {
132
+ const privateKey = agent . privateKey ;
133
+ const message = `${ subject } ${ getTimestampNow ( ) } ` ;
134
+ const signed = await signToBase64 ( message , privateKey ) ;
135
+ headers . set ( 'x-atomic-signature' , signed ) ;
136
+ return headers ;
137
+ }
0 commit comments