Skip to content

Commit 92245d4

Browse files
committed
wip: combined lit action
1 parent 92c2b85 commit 92245d4

File tree

4 files changed

+177
-40
lines changed

4 files changed

+177
-40
lines changed

local-tests/tests/testUseTriaAuthAndWrappedKeysSessionSigsGen.ts

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,11 @@ export const testUseTriaAuthAndWrappedKeysSessionSigsGen = async (
2424
const alice = await devEnv.createRandomPerson();
2525

2626
// -- Start
27+
const triaAuthMethod = {
28+
// authMethodId: '', <-- Tria's managing this by permitting auth method to the user id
29+
authMethodType: process.env.TRIA_AUTHMETHOD_TYPE,
30+
accessToken: process.env.TRIA_ACCESS_TOKEN,
31+
};
2732

2833
// -- mint a pkp
2934
console.log(`🔄 Minting new PKP...`);
@@ -85,8 +90,8 @@ export const testUseTriaAuthAndWrappedKeysSessionSigsGen = async (
8590
const evmMessageToSign = 'This is a test evm message';
8691

8792
const { results } = await triaBatchGeneratePrivateKeys({
88-
ipfsId: hashOfLitActionCode,
8993
pkpPublicKey: pkp.publicKey,
94+
ipfsId: hashOfLitActionCode,
9095
actions: [
9196
{
9297
network: 'evm',
@@ -100,8 +105,10 @@ export const testUseTriaAuthAndWrappedKeysSessionSigsGen = async (
100105
},
101106
],
102107
litNodeClient: devEnv.litNodeClient,
108+
authMethod: triaAuthMethod,
103109
});
104110

111+
console.log("results:", results);
105112

106113
process.exit();
107114

packages/wrapped-keys-lit-actions/src/lib/common/bespoke/tria_batchGenerateEncryptedKeys.js

Lines changed: 138 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ const {
1111
const { signMessageSolanaKey } = require('../../solana/internal/signMessage');
1212

1313
/* "TRIA" global accessControlConditions, actions, Lit*/
14-
1514
async function processEthereumAction(action) {
1615
const { network, generateKeyParams } = action;
1716
const messageToSign = action.signMessageParams?.messageToSign;
@@ -94,16 +93,43 @@ async function processActions(actions) {
9493
);
9594
}
9695

97-
function validateParams(actions) {
98-
if (!actions) {
96+
/**
97+
* - jsParams: Expected data type: Object (e.g., "{ authMethod: { accessToken: '...', authMethodType: '...' }, publicKey: '...', actions: [...] }")
98+
*
99+
* This parameter is an object containing the following properties:
100+
* - authMethod
101+
* - publicKey
102+
* - actions: Array of action objects, each containing network and key generation params.
103+
*
104+
*/
105+
function validateJsParams(jsParams) {
106+
if (!jsParams.authMethod) {
107+
throw new Error('Missing required field: authMethod');
108+
}
109+
if (!jsParams.publicKey) {
110+
throw new Error('Missing required field: publicKey');
111+
}
112+
if (!jsParams.accessControlConditions) {
113+
throw new Error('Missing required field: accessControlConditions');
114+
}
115+
const { accessToken, authMethodType } = jsParams.authMethod;
116+
117+
if (!accessToken) {
118+
throw new Error('Missing required field: authMethod.accessToken');
119+
}
120+
if (!authMethodType) {
121+
throw new Error('Missing required field: authMethod.authMethodType');
122+
}
123+
124+
if (!jsParams.actions) {
99125
throw new Error('Missing required field: actions');
100126
}
101127

102-
if (!actions.length) {
128+
if (!jsParams.actions.length) {
103129
throw new Error('No actions provided (empty array?)');
104130
}
105131

106-
actions.forEach((action, ndx) => {
132+
jsParams.actions.forEach((action, ndx) => {
107133
if (!['evm', 'solana'].includes(action.network)) {
108134
throw new Error(
109135
`Invalid field: actions[${ndx}].network: ${action.network}`
@@ -149,9 +175,114 @@ function validateParams(actions) {
149175
// })();
150176

151177
const go = async () => {
152-
LitActions.setResponse({
153-
response: "(true, 'Something else is here!')",
178+
// ========== Tria's Logic ==========
179+
// Lit Action:: Prepare jsParams
180+
const jsParams = {
181+
authMethod: {
182+
accessToken: authMethod.accessToken,
183+
authMethodType: authMethod.authMethodType,
184+
},
185+
publicKey: publicKey,
186+
actions: actions,
187+
accessControlConditions: accessControlConditions,
188+
};
189+
190+
validateJsParams(jsParams);
191+
192+
// ========== Tria's Logic ==========
193+
194+
// Authentication
195+
const url = 'https://api.development.tria.so/api/v1/user/info';
196+
const response = await fetch(url, {
197+
method: 'GET',
198+
headers: {
199+
Authorization: `Bearer ${jsParams.authMethod.accessToken}`,
200+
},
154201
});
202+
const data = await response.json();
203+
console.log('data', data);
204+
205+
if (!data.success) {
206+
Lit.Actions.setResponse({
207+
response: JSON.stringify({
208+
success: false,
209+
message: 'Authentication Failed',
210+
}),
211+
});
212+
return;
213+
}
214+
215+
// Authorization:: Prepare params
216+
// -- 1. get the authMethodId from unique identify from the response
217+
const authMethodId = `${ethers.utils.keccak256(
218+
ethers.utils.toUtf8Bytes(data.userInfo.uuid)
219+
)}`;
220+
console.log('Computed AuthMethodId', authMethodId);
221+
222+
// -- 2. get the PKP token id
223+
const tokenId = Lit.Actions.pubkeyToTokenId({
224+
publicKey: jsParams.publicKey,
225+
});
226+
console.log('tokenId', tokenId);
227+
228+
// -- 3. get the permitted auth methods of the PKP token id
229+
const permittedAuthMethods = await Lit.Actions.getPermittedAuthMethods({
230+
tokenId,
231+
});
232+
console.log('permittedAuthMethods', permittedAuthMethods);
233+
234+
// -- 4. only get where authMethod that's equal to the authMethod Id
235+
const permittedAuthMethod = permittedAuthMethods.find(
236+
(method) => method.id === authMethodId
237+
);
238+
console.log('permittedAuthMethod', permittedAuthMethod);
239+
240+
// TODO: Uncomment this block to enable Authorization
241+
// Authorization:: Failed Authentication and Authorization
242+
// if (
243+
// !permittedAuthMethod ||
244+
// permittedAuthMethod.auth_method_type !== jsParams.authMethod.authMethodType
245+
// ) {
246+
// Lit.Actions.setResponse({
247+
// response: JSON.stringify({
248+
// success: false,
249+
// message: 'Authorization Failed',
250+
// }),
251+
// });
252+
// return;
253+
// }
254+
255+
// LitActions.setResponse({
256+
// response: `(true, ${JSON.stringify({
257+
// returnedData: data,
258+
// logs: {
259+
// authMethodId,
260+
// tokenId,
261+
// permittedAuthMethods,
262+
// permittedAuthMethod,
263+
// actions: jsParams.actions,
264+
// batchGeneratePrivateKeysActionResult,
265+
// },
266+
// })})`,
267+
// });
268+
269+
try {
270+
const batchGeneratePrivateKeysActionResult = await processActions(
271+
jsParams.actions
272+
);
273+
274+
Lit.Actions.setResponse({
275+
response: JSON.stringify(
276+
`(true, ${JSON.stringify(batchGeneratePrivateKeysActionResult)})`
277+
),
278+
});
279+
280+
// 1. Generate both EVM and solana private keys
281+
// 2. Run appropriate signMessage for each key _and_ encrypt the keys for persistence to wrapped-keys backend
282+
// 3. Return results for both signMessage ops and both encrypted key payloads for persistence
283+
} catch (err) {
284+
Lit.Actions.setResponse({ response: `Error: ${err.message}` });
285+
}
155286
};
156287

157288
go();

packages/wrapped-keys-lit-actions/test.ts

Lines changed: 0 additions & 21 deletions
This file was deleted.

packages/wrapped-keys/src/lib/api/bespoke/tria-batch-generate-private-keys.ts

Lines changed: 31 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -15,16 +15,7 @@ import {
1515
import { LitAbility, LitActionResource, LitPKPResource } from '@lit-protocol/auth-helpers';
1616
import { SessionSigsMap } from '@lit-protocol/types';
1717
import { formatSessionSigsJSON, getResourcesFromSessionSigs } from '@lit-protocol/misc';
18-
19-
// resolvedAuthContext: {
20-
// auth_context: {
21-
// actionIpfsIds: [ 'Qmd5ibCRo9DhEnjcmfBsMU6qRBCvMCZw5kB7oSvCa7iXDR' ],
22-
// authMethodContexts: [],
23-
// authSigAddress: null,
24-
// customAuthResource: "(true, 'Anything your want to use in executeJs')",
25-
// resources: []
26-
// }
27-
// }
18+
import { computeAddress } from 'ethers/lib/utils';
2819

2920

3021
/**
@@ -37,6 +28,10 @@ export async function triaBatchGeneratePrivateKeys(
3728
params: Omit<BatchGeneratePrivateKeysParams, 'pkpSessionSigs'> & {
3829
pkpPublicKey: string | `0x${string}`;
3930
ipfsId: string | `Qm${string}`;
31+
authMethod: {
32+
authMethodType: string | `0x${string}`;
33+
accessToken: string | `eyJ${string}`;
34+
}
4035
}
4136
): Promise<BatchGeneratePrivateKeysResult> {
4237

@@ -60,10 +55,35 @@ export async function triaBatchGeneratePrivateKeys(
6055
// 'tria_batchGenerateEncryptedKeys'
6156
// );
6257

58+
let pkpPubKey = params.pkpPublicKey;
59+
60+
if (pkpPubKey.startsWith('0x')) {
61+
pkpPubKey = pkpPubKey.slice(2);
62+
}
63+
const pkpPubkeyBuffer = Buffer.from(pkpPubKey, 'hex');
64+
65+
const pkpEthAddress = computeAddress(pkpPubkeyBuffer);
66+
67+
console.log("pkpEthAddress:", pkpEthAddress);
68+
69+
const allowPkpAddressToDecrypt = getPkpAccessControlCondition(pkpEthAddress);
70+
6371
// Here we should use getLitActionSessionSigs rather than executeJs
6472
console.log(`🔄 Getting Lit Action Session Sigs`);
6573
let litActionSessionSigs: SessionSigsMap;
6674

75+
const _jsParams = {
76+
authMethod: {
77+
accessToken: params.authMethod.accessToken,
78+
authMethodType: params.authMethod.authMethodType,
79+
},
80+
actions: params.actions,
81+
publicKey: params.pkpPublicKey,
82+
accessControlConditions: [allowPkpAddressToDecrypt],
83+
};
84+
85+
console.log("_jsParams:", _jsParams);
86+
6787
try {
6888
litActionSessionSigs = await params.litNodeClient.getLitActionSessionSigs({
6989
pkpPublicKey: params.pkpPublicKey,
@@ -78,7 +98,7 @@ export async function triaBatchGeneratePrivateKeys(
7898
},
7999
],
80100
litActionIpfsId: params.ipfsId,
81-
jsParams: {},
101+
jsParams: _jsParams,
82102
});
83103
} catch (e) {
84104
throw new Error(`Error getting Lit Action Session Sigs: ${e}`);

0 commit comments

Comments
 (0)