-
Notifications
You must be signed in to change notification settings - Fork 1
/
siwfV2.service.ts
252 lines (228 loc) · 9.65 KB
/
siwfV2.service.ts
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
import { BadRequestException, Inject, Injectable, Logger } from '@nestjs/common';
import {
generateEncodedSignedRequest,
generateAuthenticationUrl,
VerifiedPhoneNumberCredential,
VerifiedEmailAddressCredential,
VerifiedGraphKeyCredential,
SiwfCredentialRequest,
SiwfResponse,
validateSiwfResponse,
getLoginResult,
isCredentialEmail,
isCredentialPhone,
isCredentialGraph,
hasChainSubmissions,
isPayloadLogin,
isPayloadAddProvider,
SiwfResponsePayload,
} from '@projectlibertylabs/siwfv2';
import apiConfig, { IAccountApiConfig } from '#account-api/api.config';
import blockchainConfig, { IBlockchainConfig } from '#blockchain/blockchain.config';
import { BlockchainRpcQueryService } from '#blockchain/blockchain-rpc-query.service';
import { EnqueueService } from '#account-lib/services/enqueue-request.service';
import { WalletV2RedirectResponseDto } from '#types/dtos/account/wallet.v2.redirect.response.dto';
import { WalletV2LoginRequestDto } from '#types/dtos/account/wallet.v2.login.request.dto';
import { WalletV2LoginResponseDto } from '#types/dtos/account/wallet.v2.login.response.dto';
import { PublishSIWFSignupRequestDto, SIWFEncodedExtrinsic, TransactionResponse } from '#types/dtos/account';
import { TransactionType } from '#types/account-webhook';
import { isNotNull } from '#utils/common/common.utils';
import { chainSignature, statefulStoragePayload } from '#utils/common/signature.util';
import { ApiPromise } from '@polkadot/api';
@Injectable()
export class SiwfV2Service {
private readonly logger: Logger;
constructor(
@Inject(apiConfig.KEY) private readonly apiConf: IAccountApiConfig,
@Inject(blockchainConfig.KEY) private readonly blockchainConf: IBlockchainConfig,
private blockchainService: BlockchainRpcQueryService,
private enqueueService: EnqueueService,
) {
this.logger = new Logger(this.constructor.name);
}
private static requestedCredentialTypesToFullRequest(requestCredentials: string[]): SiwfCredentialRequest[] {
const credentials: SiwfCredentialRequest[] = [];
if (
requestCredentials.includes('VerifiedEmailAddressCredential') &&
requestCredentials.includes('VerifiedPhoneNumberCredential')
) {
credentials.push({
anyOf: [VerifiedEmailAddressCredential, VerifiedPhoneNumberCredential],
});
} else if (requestCredentials.includes('VerifiedEmailAddressCredential')) {
credentials.push({
anyOf: [VerifiedEmailAddressCredential],
});
} else if (requestCredentials.includes('VerifiedPhoneNumberCredential')) {
credentials.push({
anyOf: [VerifiedPhoneNumberCredential],
});
}
if (requestCredentials.includes('VerifiedGraphKeyCredential')) {
credentials.push(VerifiedGraphKeyCredential);
}
return credentials;
}
// Default to the default "production" and "staging" endpoints for mainnet and testnet-paseo
private swifV2Endpoint(): string {
const { siwfV2Url }: IAccountApiConfig = this.apiConf;
if (siwfV2Url) return siwfV2Url;
const networkType = this.blockchainService.getNetworkType();
if (networkType === 'mainnet') return 'production';
if (networkType === 'testnet-paseo') return 'staging';
throw new Error(
'Unable to derive the SIWF V2 Redirect URL endpoint. Unknown networks require setting "SIWF_V2_URL"',
);
}
private async siwfV2PayloadToEncodedExtrinsic(
payload: SiwfResponsePayload,
userPublicKey: string,
): Promise<SIWFEncodedExtrinsic | null> {
if (!payload.endpoint) {
return null;
}
const api = await this.blockchainService.getApi();
const { pallet, extrinsic: extrinsicName } = payload.endpoint;
switch (`${pallet}.${extrinsicName}`) {
case 'handles.claimHandle':
case 'msa.grantDelegation':
case 'msa.createSponsoredAccountWithDelegation':
return {
pallet,
extrinsicName,
encodedExtrinsic: api.tx[pallet][extrinsicName](
userPublicKey,
chainSignature(payload.signature),
payload.payload,
).toHex(),
};
case 'statefulStorage.applyItemActionsWithSignatureV2':
return {
pallet,
extrinsicName,
encodedExtrinsic: (api as ApiPromise).tx.statefulStorage
.applyItemActionsWithSignatureV2(
userPublicKey,
chainSignature(payload.signature),
// TS is not smart enough to figure it out from the case
statefulStoragePayload(api.registry, payload.payload as any),
)
.toHex(),
};
default:
throw new Error(`Unknown payload request: ${pallet}.${extrinsicName}`);
}
}
async getPayload(request: WalletV2LoginRequestDto): Promise<SiwfResponse> {
let payload: SiwfResponse;
const loginMsgURIValidation = this.apiConf.siwfV2URIValidation;
if (request.authorizationPayload) {
try {
// Await here so the error is caught
payload = await validateSiwfResponse(request.authorizationPayload, loginMsgURIValidation);
} catch (e) {
this.logger.warn('Failed to parse "authorizationPayload"', { error: e.toString() });
throw new BadRequestException('Invalid `authorizationPayload` in request.');
}
} else if (request.authorizationCode) {
// This is used by Frequency Access
try {
payload = await getLoginResult(request.authorizationCode, {
endpoint: this.swifV2Endpoint(),
loginMsgUri: loginMsgURIValidation,
});
} catch (e) {
this.logger.warn('Failed to retrieve valid payload from "authorizationCode"', { error: e.toString() });
throw new BadRequestException('Invalid response from `authorizationCode` payload fetch.');
}
} else {
throw new BadRequestException('No `authorizationPayload` or `authorizationCode` in request.');
}
const login = payload.payloads.find(isPayloadLogin);
const addProvider = payload.payloads.find(isPayloadAddProvider);
// Make sure this either is a login OR delegation
if (!login && !addProvider) {
throw new BadRequestException(
'Received a WalletV2LoginRequestDto that has neither a login NOR an add provider payload.',
);
} else if (login) {
// Make sure the login is for me!
// @todo
} else if (addProvider) {
// Make sure I'm the provider
if (addProvider.payload.authorizedMsaId.toString() !== this.blockchainConf.providerId.toString()) {
this.logger.error(
`Got a request to add the Provider Id "${addProvider.payload.authorizedMsaId}", but configured for Provider Id: "${this.blockchainConf.providerId.toString()}"`,
);
throw new BadRequestException('Received a request for the wrong Provider Id.');
}
}
return payload;
}
async getSiwfV2LoginResponse(payload: SiwfResponse): Promise<WalletV2LoginResponseDto> {
const response = new WalletV2LoginResponseDto();
response.controlKey = payload.userPublicKey.encodedValue;
// Try to look up the MSA id, if there is no createSponsoredAccountWithDelegation request
if (payload.payloads.every((x) => x.endpoint?.extrinsic !== 'createSponsoredAccountWithDelegation')) {
// Get the MSA Id from the chain
const msaId = await this.blockchainService.publicKeyToMsaId(response.controlKey);
if (msaId) response.msaId = msaId;
}
// Parse out the email, phone, and graph
const email = payload.credentials.find(isCredentialEmail)?.credentialSubject.emailAddress;
if (email) response.email = email;
const phoneNumber = payload.credentials.find(isCredentialPhone)?.credentialSubject.phoneNumber;
if (phoneNumber) response.phoneNumber = phoneNumber;
const graphKey = payload.credentials.find(isCredentialGraph)?.credentialSubject;
if (graphKey) response.graphKey = graphKey;
response.rawCredentials = payload.credentials;
return response;
}
async queueChainActions(response: SiwfResponse): Promise<TransactionResponse | null> {
// Don't do anything if there is nothing to do
if (!hasChainSubmissions(response)) return null;
try {
const calls: PublishSIWFSignupRequestDto['calls'] = (
await Promise.all(
response.payloads.map((p) => this.siwfV2PayloadToEncodedExtrinsic(p, response.userPublicKey.encodedValue)),
)
).filter(isNotNull);
return this.enqueueService.enqueueRequest<PublishSIWFSignupRequestDto>({
calls,
type: TransactionType.SIWF_SIGNUP,
});
} catch (e) {
this.logger.warn('Error during SIWF V2 Chain Action Queuing', { error: e.toString() });
throw new BadRequestException('Failed to process payloads');
}
}
async getRedirectUrl(
callbackUrl: string,
permissions: number[],
requestCredentials: string[],
): Promise<WalletV2RedirectResponseDto> {
let response: WalletV2RedirectResponseDto;
try {
const { siwfNodeRpcUrl }: IAccountApiConfig = this.apiConf;
const { providerSeedPhrase } = this.blockchainConf;
const signedRequest = await generateEncodedSignedRequest(
providerSeedPhrase,
callbackUrl,
permissions,
SiwfV2Service.requestedCredentialTypesToFullRequest(requestCredentials),
);
const frequencyRpcUrl = siwfNodeRpcUrl.toString();
response = {
signedRequest,
redirectUrl: generateAuthenticationUrl(signedRequest, new URLSearchParams({ frequencyRpcUrl }), {
endpoint: this.swifV2Endpoint(),
}),
frequencyRpcUrl,
};
} catch (e) {
this.logger.warn('Error during SIWF V2 Redrect URL request', { error: e.toString() });
throw new BadRequestException('Failed to get SIWF V2 Redirect URL');
}
return response;
}
}