Skip to content

Commit e0ad79d

Browse files
committed
#108 x-atomic-signature
1 parent e23f006 commit e0ad79d

File tree

2 files changed

+32
-4
lines changed

2 files changed

+32
-4
lines changed

lib/src/client.ts

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1-
import { Store } from '.';
2-
import { Commit, serializeDeterministically } from './commit';
1+
import { getTimestampNow, Store } from '.';
2+
import { Commit, serializeDeterministically, signToBase64 } from './commit';
33
import { parseJsonADResource } from './parse';
44
import { Resource } from './resource';
5+
import { Agent } from '@tomic/lib';
56

67
/**
78
* Fetches and Parses a Resource. Can fetch through another atomic server if you
@@ -26,6 +27,10 @@ export async function fetchResource(
2627
tryValidURL(subject);
2728
const requestHeaders: HeadersInit = new Headers();
2829
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));
2934
let url = subject;
3035
if (from !== undefined) {
3136
const newURL = new URL(`${from}/path`);
@@ -116,3 +121,17 @@ export function removeQueryParamsFromURL(subject: string): string {
116121
// return subject.split('?')[0];
117122
return subject;
118123
}
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+
}

lib/src/commit.ts

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,11 @@ export interface CommitBuilderI {
1717
destroy?: boolean;
1818
}
1919

20+
/** Return the current time as Atomic Data timestamp. Milliseconds since unix epoch. */
21+
export function getTimestampNow(): number {
22+
return Math.round(new Date().getTime());
23+
}
24+
2025
/** A {@link Commit} without its signature, signer and timestamp */
2126
export class CommitBuilder implements CommitBuilderI {
2227
subject: string;
@@ -36,8 +41,12 @@ export class CommitBuilder implements CommitBuilderI {
3641
* Commit which is ready to be sent to an Atomic-Server `/commit` endpoint.
3742
*/
3843
async sign(privateKey: string, agentSubject: string): Promise<Commit> {
39-
const now: number = Math.round(new Date().getTime());
40-
const commit = await signAt(this.clone(), agentSubject, privateKey, now);
44+
const commit = await signAt(
45+
this.clone(),
46+
agentSubject,
47+
privateKey,
48+
getTimestampNow(),
49+
);
4150
return commit;
4251
}
4352

0 commit comments

Comments
 (0)