-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathAuthSignToken.ts
More file actions
59 lines (55 loc) · 1.97 KB
/
AuthSignToken.ts
File metadata and controls
59 lines (55 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import type {
ClientRPCRequestParams,
ClientRPCResponseResult,
IdentityRequestData,
IdentityResponseData,
TokenIdentityRequest,
TokenIdentityResponse,
} from '../types.js';
import type KeyRing from '../../keys/KeyRing.js';
import type { PublicKey } from '../../keys/types.js';
import { UnaryHandler } from '@matrixai/rpc';
import Token from '../../tokens/Token.js';
import * as clientErrors from '../errors.js';
import * as nodesUtils from '../../nodes/utils.js';
class AuthSignToken extends UnaryHandler<
{
keyRing: KeyRing;
},
ClientRPCRequestParams<TokenIdentityRequest>,
ClientRPCResponseResult<TokenIdentityResponse>
> {
public handle = async (
input: ClientRPCRequestParams<TokenIdentityRequest>,
): Promise<TokenIdentityResponse> => {
const { keyRing }: { keyRing: KeyRing } = this.container;
// Get and verify incoming node
const inputToken = { payload: input.payload, signatures: input.signatures };
const incomingToken = Token.fromEncoded<IdentityRequestData>(inputToken);
if (!('publicKey' in incomingToken.payload)) {
throw new clientErrors.ErrorClientAuthenticationInvalidToken(
'Input token does not contain public key',
);
}
const incomingPublicKey = Buffer.from(
incomingToken.payload.publicKey,
'base64url',
) as PublicKey;
if (!incomingToken.verifyWithPublicKey(incomingPublicKey)) {
throw new clientErrors.ErrorClientAuthenticationInvalidToken(
'Incoming token does not match its signature',
);
}
// Create the outgoing token with the incoming token integrated into the
// payload.
const outgoingTokenPayload: IdentityResponseData = {
requestToken: inputToken,
nodeId: nodesUtils.encodeNodeId(keyRing.getNodeId()),
};
const outgoingToken =
Token.fromPayload<IdentityResponseData>(outgoingTokenPayload);
outgoingToken.signWithPrivateKey(keyRing.keyPair);
return outgoingToken.toEncoded();
};
}
export default AuthSignToken;