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