Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,406 changes: 0 additions & 1,406 deletions apps/lit-auth-service/bun.lock

This file was deleted.

1,397 changes: 0 additions & 1,397 deletions apps/lit-login-service/bun.lock

This file was deleted.

290 changes: 170 additions & 120 deletions bun.lock

Large diffs are not rendered by default.

155 changes: 155 additions & 0 deletions e2e/src/demo/add-permitted-address-demo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
// Run this command for this demo:
// LOG_LEVEL=silent NETWORK=naga-dev bun run ./e2e/src/demo/add-permitted-address-demo.ts

//
// This test if a PKP EOA Auth Method could add a permitted address via the PKPViemAccount
//
import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts';
import { nonceManager } from 'viem';
import { fundAccount } from '../helper/fundAccount';
import { createLitClient } from '@lit-protocol/lit-client';
import {
createAuthManager,
storagePlugins,
ViemAccountAuthenticator,
} from '@lit-protocol/auth';

// -- Configurations
const { nagaLocal } = await import('@lit-protocol/networks');
const LOCAL_NETWORK_FUNDING_AMOUNT = '1';

// -- Master account to fund the alice(test) account
const localMasterAccount = privateKeyToAccount(
process.env['LOCAL_MASTER_ACCOUNT'] as `0x${string}`,
{
nonceManager: nonceManager,
}
);

// -- EOA Test account via Viem
const aliceViemAccount = privateKeyToAccount(generatePrivateKey());

// -- Using the authenticator to get the Auth Data
const aliceViemAccountAuthData = await ViemAccountAuthenticator.authenticate(
aliceViemAccount
);

console.log("✅ aliceViemAccountAuthData:", aliceViemAccountAuthData);

try {
await fundAccount(aliceViemAccount, localMasterAccount, nagaLocal, {
ifLessThan: LOCAL_NETWORK_FUNDING_AMOUNT,
thenFundWith: LOCAL_NETWORK_FUNDING_AMOUNT,
});
console.log("✅ Account Funded.")
} catch (e) {
throw new Error("❌ Failed to fund account.")
}

/**
* ====================================
* Initialise the LitClient
* ====================================
*/
const litClient = await createLitClient({ network: nagaLocal });
console.log("✅ Created Lit Client")

/**
* ====================================
* Initialise the AuthManager
* ====================================
*/
const authManager = createAuthManager({
storage: storagePlugins.localStorageNode({
appName: 'my-local-testing-app',
networkName: 'local-test',
storagePath: './lit-auth-local',
}),
});
console.log("✅ Created Auth Manager")

// Minting a new PKP
const tx = await litClient.mintWithAuth({
account: aliceViemAccount,
authData: aliceViemAccountAuthData,
scopes: ['sign-anything'],
});
console.log("✅ TX 1 done");
console.log("ℹ️ tx:", tx)

const pkpInfo = tx.data;
console.log("✅ pkpInfo:", pkpInfo);

const pkpPermissionsManagerForAliceViemAccount = await litClient.getPKPPermissionsManager({
pkpIdentifier: {
tokenId: pkpInfo.tokenId,
},
account: aliceViemAccount,
});

console.log("✅ pkpPermissionsManagerForAliceViemAccount:", await pkpPermissionsManagerForAliceViemAccount.getPermissionsContext());

// check is address permitted
const aliceViemAccountIsPermitted = await pkpPermissionsManagerForAliceViemAccount.isPermittedAddress({
address: aliceViemAccount.address,
});

console.log(`❗️ ${aliceViemAccount.address} is ${aliceViemAccountIsPermitted ? 'permitted' : 'NOT permitted'}`);

// check if pkp address is permitted
const pkpIsPermitted = await pkpPermissionsManagerForAliceViemAccount.isPermittedAddress({
address: pkpInfo.ethAddress,
});

console.log(`❗️ ${pkpInfo.ethAddress} is ${pkpIsPermitted ? 'permitted' : 'NOT permitted'}`);


const authContext = await authManager.createPkpAuthContext({
authData: aliceViemAccountAuthData,
pkpPublicKey: pkpInfo.pubkey,
authConfig: {
capabilityAuthSigs: [],
expiration: new Date(Date.now() + 1000 * 60 * 60 * 24).toISOString(),
statement: "",
domain: "",
resources: [
["pkp-signing", "*"],
["lit-action-execution", "*"],
],
},
litClient,
});

console.log("authContext:", authContext);

const pkpViemAccount = await litClient.getPkpViemAccount({
pkpPublicKey: pkpInfo.pubkey,
authContext: authContext,
chainConfig: nagaLocal.getChainConfig(),
});

await fundAccount(pkpViemAccount, localMasterAccount, nagaLocal, {
ifLessThan: LOCAL_NETWORK_FUNDING_AMOUNT,
thenFundWith: LOCAL_NETWORK_FUNDING_AMOUNT,
});

const pkpViemAccountPermissionsManager = await litClient.getPKPPermissionsManager({
pkpIdentifier: {
tokenId: pkpInfo.tokenId,
},
account: pkpViemAccount,
});

try {
const tx2 = await pkpViemAccountPermissionsManager.addPermittedAddress({
address: "0x1234567890123456789012345678901234567890",
scopes: ["sign-anything"],
});
console.log('tx2:', tx2)
} catch (e) {
throw new Error(e);
}

console.log("✅ pkpViemAccountPermissionsManager:", await pkpViemAccountPermissionsManager.getPermissionsContext());

process.exit();
22 changes: 11 additions & 11 deletions e2e/src/e2e.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ describe('all', () => {
ctx = await init();

// Create PKP and custom auth contexts using helper functions
alicePkpAuthContext = await createPkpAuthContext(ctx);
// alicePkpAuthContext = await createPkpAuthContext(ctx);
aliceCustomAuthContext = await createCustomAuthContext(ctx);
} catch (e) {
console.error(e);
Expand Down Expand Up @@ -83,29 +83,29 @@ describe('all', () => {
console.log('🔐 Testing using Programmable Key Pair authentication');

describe('endpoints', () => {
it('pkpSign', () => createPkpSignTest(ctx, () => alicePkpAuthContext)());
it('pkpSign', () => createPkpSignTest(ctx, () => ctx.alicePkpAuthContext)());
it('executeJs', () =>
createExecuteJsTest(ctx, () => alicePkpAuthContext)());
createExecuteJsTest(ctx, () => ctx.alicePkpAuthContext)());
it('viewPKPsByAddress', () =>
createViewPKPsByAddressTest(ctx, () => alicePkpAuthContext)());
createViewPKPsByAddressTest(ctx, () => ctx.alicePkpAuthContext)());
it('viewPKPsByAuthData', () =>
createViewPKPsByAuthDataTest(ctx, () => alicePkpAuthContext)());
createViewPKPsByAuthDataTest(ctx, () => ctx.alicePkpAuthContext)());
it('pkpEncryptDecrypt', () =>
createPkpEncryptDecryptTest(ctx, () => alicePkpAuthContext)());
createPkpEncryptDecryptTest(ctx, () => ctx.alicePkpAuthContext)());
it('encryptDecryptFlow', () =>
createEncryptDecryptFlowTest(ctx, () => alicePkpAuthContext)());
createEncryptDecryptFlowTest(ctx, () => ctx.alicePkpAuthContext)());
it('pkpPermissionsManagerFlow', () =>
createPkpPermissionsManagerFlowTest(ctx, () => alicePkpAuthContext)());
createPkpPermissionsManagerFlowTest(ctx, () => ctx.alicePkpAuthContext)());
});

describe('integrations', () => {
describe('pkp viem account', () => {
it('sign message', () =>
createViemSignMessageTest(ctx, () => alicePkpAuthContext)());
createViemSignMessageTest(ctx, () => ctx.alicePkpAuthContext)());
it('sign transaction', () =>
createViemSignTransactionTest(ctx, () => alicePkpAuthContext)());
createViemSignTransactionTest(ctx, () => ctx.alicePkpAuthContext)());
it('sign typed data', () =>
createViemSignTypedDataTest(ctx, () => alicePkpAuthContext)());
createViemSignTypedDataTest(ctx, () => ctx.alicePkpAuthContext)());
});
});
});
Expand Down
76 changes: 76 additions & 0 deletions e2e/src/helper/pkp-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/**
* PKP Utilities
*
* This module provides utility functions for managing Programmable Key Pairs (PKPs)
* in the Lit Protocol ecosystem. It handles the common pattern of checking for
* existing PKPs and creating new ones when necessary.
*
* Usage:
* import { getOrCreatePkp } from './helper/pkp-utils';
* const pkp = await getOrCreatePkp(litClient, authData, account, storagePath, networkName);
*/

import { storagePlugins } from '@lit-protocol/auth';

// Configuration constants
const PAGINATION_LIMIT = 5;
const APP_NAME = 'my-app';
const PKP_SCOPES = ['sign-anything'];

/**
* Gets an existing PKP or creates a new one if none exists
*
* @param litClient - The Lit Protocol client instance
* @param authData - Authentication data for the account
* @param account - The account to associate with the PKP
* @param storagePath - Local storage path for PKP tokens
* @param networkName - Name of the network being used
* @returns Promise<PKP> - The existing or newly created PKP
*/
export const getOrCreatePkp = async (
litClient: any,
authData: any,
account: any,
storagePath: string,
networkName: string
) => {
// Check for existing PKPs
const { pkps } = await litClient.viewPKPsByAuthData({
authData,
pagination: {
limit: PAGINATION_LIMIT,
},
storageProvider: storagePlugins.localStorageNode({
appName: APP_NAME,
networkName,
storagePath,
}),
});

// If PKP exists, return it
if (pkps && pkps[0]) {
return pkps[0];
}

// Otherwise mint new PKP
const mintResult = await litClient.mintWithAuth({
authData,
account,
scopes: PKP_SCOPES,
});

// Query again to get the newly minted PKP in the expected format
const { pkps: newPkps } = await litClient.viewPKPsByAuthData({
authData,
pagination: {
limit: PAGINATION_LIMIT,
},
storageProvider: storagePlugins.localStorageNode({
appName: APP_NAME,
networkName,
storagePath,
}),
});

return newPkps[0];
};
12 changes: 3 additions & 9 deletions e2e/src/helper/tests/encrypt-decrypt-flow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,9 @@ export const createEncryptDecryptFlowTest = (
const { createAccBuilder } = await import(
'@lit-protocol/access-control-conditions'
);
const { generatePrivateKey, privateKeyToAccount } = await import(
'viem/accounts'
);

const authContext = getAuthContext();

// Create a test account for Bob (recipient)
const bobAccount = privateKeyToAccount(generatePrivateKey());

// Determine which address to use for Alice based on auth context type
let aliceAddress: string;
if (authContext === ctx.aliceEoaAuthContext) {
Expand All @@ -29,7 +23,7 @@ export const createEncryptDecryptFlowTest = (
// Set up access control conditions requiring Bob's wallet ownership
const builder = createAccBuilder();
const accs = builder
.requireWalletOwnership(bobAccount.address)
.requireWalletOwnership(ctx.bobViemAccount.address)
.on('ethereum')
.build();

Expand All @@ -50,7 +44,7 @@ export const createEncryptDecryptFlowTest = (
const jsonData = {
message: 'Test JSON data',
sender: aliceAddress,
recipient: bobAccount.address,
recipient: ctx.bobViemAccount.address,
timestamp: Date.now(),
};

Expand Down Expand Up @@ -105,7 +99,7 @@ export const createEncryptDecryptFlowTest = (
// Create Bob's auth context for decryption
const bobAuthContext = await ctx.authManager.createEoaAuthContext({
config: {
account: bobAccount,
account: ctx.bobViemAccount,
},
authConfig: {
domain: 'localhost',
Expand Down
Loading
Loading