-
Notifications
You must be signed in to change notification settings - Fork 2
New issue
Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? # to your account
feat: add support for large file encryption #3
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,113 @@ | ||
import * as fs from 'fs' | ||
import { ethers } from 'ethers' | ||
import { Readable } from 'stream' | ||
import { Signer } from '@ucanto/principal/ed25519' | ||
|
||
import env from '../env.js' | ||
import { getLit, getSessionSigs, getCapacityCredits, decryptWithKeyTo } from '../lib.js' | ||
import { createDecryptWrappedInvocation } from '../decrypt-capability.js' | ||
|
||
/** | ||
* rootCid - The CID of the encrypted data file uploaded to Storacha. | ||
* delegationFilePath - Path to the delegation CAR file | ||
* outputPath - output file to write the decrypted content | ||
* capacityTokenId - If you already have a capacity credit token ID (optional) | ||
*/ | ||
async function main() { | ||
const rootCid = process.argv[2] | ||
const delegationFilePath = process.argv[3] | ||
const outputPath = process.argv[4] | ||
/**@type {string | null} */ | ||
let capacityTokenId = process.argv[5] | ||
|
||
const response = await fetch(`https://${rootCid}.ipfs.w3s.link`) | ||
if (!response.ok) { | ||
throw new Error(`Failed to fetch: ${response.status} ${response.statusText}`) | ||
} | ||
|
||
let encryptedContent = await response.text() | ||
console.log('Encrypted content retrieved successfully:', encryptedContent) | ||
const { encryptedDataCid, ciphertext, dataToEncryptHash, accessControlConditions } = | ||
JSON.parse(encryptedContent) | ||
|
||
const encryptedDataResponse = await fetch(`https://${encryptedDataCid}.ipfs.w3s.link`) | ||
if (!encryptedDataResponse.ok || !encryptedDataResponse.body) { | ||
throw new Error(`Failed to fetch encrypted data: ${response.status} ${response.statusText}`) | ||
} | ||
|
||
const spaceDID = accessControlConditions[0].parameters[1] | ||
|
||
const litNodeClient = await getLit() | ||
const controllerWallet = new ethers.Wallet(env.WALLET_PK) | ||
|
||
if (!capacityTokenId) { | ||
console.log('🔄 No Capacity Credit provided, minting a new one...') | ||
capacityTokenId = await getCapacityCredits(controllerWallet, env.LIT_NETWORK) | ||
console.log(`✅ Minted new Capacity Credit with ID: ${capacityTokenId}`) | ||
} else { | ||
console.log(`ℹ️ Using provided Capacity Credit with ID: ${capacityTokenId}`) | ||
} | ||
|
||
// ========== SESSION SIGNATURES =========== | ||
// TODO: store the session signature (https://developer.litprotocol.com/intro/first-request/generating-session-sigs#nodejs) | ||
const sessionSigs = await getSessionSigs({ | ||
wallet: controllerWallet, | ||
accessControlConditions, | ||
dataToEncryptHash, | ||
expiration: new Date(Date.now() + 1000 * 60 * 5).toISOString() // 5 min, | ||
}) | ||
|
||
// ========== EXECUTE LIT ACTION TO DECRYPT =========== | ||
|
||
console.log('🔄 Setting UCAN delegation...') | ||
// read bytes from delegation file | ||
const delegationCarBuffer = fs.readFileSync(delegationFilePath) | ||
|
||
const decryptSigner = Signer.parse(env.DELEGATEE_AGENT_PK) | ||
console.log('Issuer:', decryptSigner.did()) | ||
|
||
const invocation = await createDecryptWrappedInvocation(delegationCarBuffer, { | ||
issuer: decryptSigner, | ||
audienceDid: env.AUTHORITY_DID_WEB, | ||
spaceDid: spaceDID, | ||
resourceCid: rootCid, | ||
expiration: new Date(Date.now() + 1000 * 60 * 10).getTime() // 10 min | ||
}) | ||
|
||
console.log('🔄 Executing Lit Action to validate UCAN and decrypt the file...') | ||
|
||
const litActionResponse = await litNodeClient.executeJs({ | ||
sessionSigs, | ||
ipfsId: env.STORACHA_LIT_ACTION_CID, | ||
jsParams: { | ||
spaceDID, | ||
ciphertext, | ||
dataToEncryptHash, | ||
accessControlConditions, | ||
invocation | ||
} | ||
}) | ||
console.log(litActionResponse) | ||
console.log('✅ Executed the Lit Action') | ||
|
||
if (!litActionResponse.response) { | ||
throw new Error('Error getting lit action response.') | ||
} | ||
const parsedResponse = JSON.parse(/** @type string*/ (litActionResponse.response)) | ||
const decryptedData = parsedResponse.decryptedString | ||
if (!decryptedData) { | ||
throw new Error('Decrypted data does not exist!') | ||
} | ||
|
||
const readStream = Readable.fromWeb( | ||
/** @type {import("stream/web").ReadableStream<any>}**/ (encryptedDataResponse.body) | ||
) | ||
await decryptWithKeyTo(decryptedData, readStream, outputPath) | ||
} | ||
|
||
main() | ||
.then(() => process.exit(0)) | ||
.catch(err => { | ||
console.error(err) | ||
process.exit(1) | ||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
import * as fs from 'fs' | ||
import * as Client from '@web3-storage/w3up-client' | ||
import * as Signer from '@ucanto/principal/ed25519' | ||
import { StoreMemory } from '@web3-storage/w3up-client/stores/memory' | ||
|
||
import env from '../env.js' | ||
import { encryptLargeFile } from '../lib.js' | ||
import { parseProof } from '../utils.js' | ||
|
||
async function main() { | ||
const filePath = process.argv[2] | ||
|
||
if (!fs.existsSync(filePath)) { | ||
throw new Error(`The path ${filePath} does not exist`) | ||
} | ||
|
||
// set up storacha client with a new agent | ||
const principal = Signer.parse(env.AGENT_PK) | ||
const store = new StoreMemory() | ||
const client = await Client.create({ principal, store }) | ||
|
||
// now give Agent the delegation from the Space | ||
const proof = await parseProof(env.PROOF) | ||
const space = await client.addSpace(proof) | ||
await client.setCurrentSpace(space.did()) | ||
|
||
// encrypt using lit | ||
/** @type import('@lit-protocol/types').AccessControlConditions */ | ||
const accessControlConditions = [ | ||
{ | ||
contractAddress: '', | ||
standardContractType: '', | ||
chain: 'ethereum', | ||
method: '', | ||
parameters: [':currentActionIpfsId', space.did()], | ||
returnValueTest: { | ||
comparator: '=', | ||
value: env.STORACHA_LIT_ACTION_CID | ||
} | ||
} | ||
] | ||
|
||
console.log('🔄 Encrypting...') | ||
const { ciphertext, dataToEncryptHash, encryptedBlobLike } = await encryptLargeFile( | ||
filePath, | ||
accessControlConditions | ||
) | ||
console.log(`✅ Encrypted file!`) | ||
console.log(`Uploading encrypted data to storacha...`) | ||
const rootEncryptedDataCid = await client.uploadFile(encryptedBlobLike) | ||
console.log(`✅ Encrypted data root cid: ${rootEncryptedDataCid}`) | ||
|
||
// upload to storacha | ||
const uploadData = { | ||
encryptedDataCid: rootEncryptedDataCid.toString(), | ||
ciphertext, | ||
dataToEncryptHash, | ||
accessControlConditions | ||
} | ||
const blob = new Blob([JSON.stringify(uploadData)]) | ||
console.log('🔄 Uploading metadata to Storacha...') | ||
const rootCid = await client.uploadFile(blob) | ||
console.log(`✅ Metadata root cid: ${rootCid}`) | ||
} | ||
|
||
main() | ||
.then(() => process.exit(0)) | ||
.catch(err => { | ||
console.error(err) | ||
process.exit(1) | ||
}) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
where is this taken from? just want to make sure we're following well established patterns for any encryption we're doing
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Oh, so this is how the Lit team recommends handling double encryption.