-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #2 from nikgraf/locker
implement locker
- Loading branch information
Showing
12 changed files
with
334 additions
and
2 deletions.
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
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,61 @@ | ||
import { useMemo } from "react"; | ||
import sodium from "react-native-libsodium"; | ||
import { decryptLocker } from "../utils/decryptLocker"; | ||
import { encryptLocker } from "../utils/encryptLocker"; | ||
import { trpc } from "../utils/trpc"; | ||
|
||
export const useLocker = (key: string) => { | ||
const createUserLockerMutation = trpc.createUserLocker.useMutation(); | ||
const latestUserLockerQuery = trpc.getLatestUserLocker.useQuery(); | ||
|
||
const keyUint8Array = sodium.from_base64(key); | ||
|
||
const content = useMemo(() => { | ||
if (!latestUserLockerQuery.data) { | ||
return null; | ||
} | ||
|
||
const contentString = decryptLocker( | ||
latestUserLockerQuery.data, | ||
keyUint8Array | ||
); | ||
return JSON.parse(contentString) || {}; // TODO validate schema | ||
}, [ | ||
latestUserLockerQuery.data?.ciphertext, | ||
latestUserLockerQuery.data?.nonce, | ||
latestUserLockerQuery.data?.commitment, | ||
latestUserLockerQuery.data?.clock, | ||
]); | ||
|
||
// RETRY in case it fails | ||
const addDocumentKey = async (documentId: string, value: string) => { | ||
const newContent = { | ||
...content, | ||
[documentId]: value, | ||
}; | ||
const newContentString = JSON.stringify(newContent); | ||
const newClock = | ||
latestUserLockerQuery.data?.clock !== undefined | ||
? latestUserLockerQuery.data.clock + 1 | ||
: 0; | ||
|
||
const { ciphertext, nonce, commitment } = encryptLocker( | ||
newContentString, | ||
newClock, | ||
keyUint8Array | ||
); | ||
|
||
await createUserLockerMutation.mutateAsync({ | ||
ciphertext, | ||
nonce, | ||
commitment, | ||
clock: newClock, | ||
}); | ||
await latestUserLockerQuery.refetch(); | ||
}; | ||
|
||
return { | ||
content, | ||
addDocumentKey, | ||
}; | ||
}; |
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,18 @@ | ||
import { decryptLocker } from "./decryptLocker"; | ||
import { encryptLocker } from "./encryptLocker"; | ||
|
||
import * as sodium from "react-native-libsodium"; | ||
|
||
beforeAll(async () => { | ||
await sodium.ready; | ||
}); | ||
|
||
// test encrypting and decrypting a locker | ||
test("encryptLocker and decryptLocker", () => { | ||
const key = new Uint8Array(32); | ||
const content = "hello world"; | ||
const clock = 1234; | ||
const encryptedLocker = encryptLocker(content, clock, key); | ||
const decryptedContent = decryptLocker(encryptedLocker, key); | ||
expect(decryptedContent).toEqual(content); | ||
}); |
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,51 @@ | ||
import canonicalize from "canonicalize"; | ||
import * as sodium from "react-native-libsodium"; | ||
|
||
type EncryptedLocker = { | ||
ciphertext: string; | ||
nonce: string; | ||
commitment: string; | ||
clock: number; | ||
}; | ||
|
||
export const decryptLocker = ( | ||
encryptedLocker: EncryptedLocker, | ||
key: Uint8Array | ||
) => { | ||
const { ciphertext, nonce, commitment, clock } = encryptedLocker; | ||
|
||
const additionalData = canonicalize({ clock }); | ||
if (!additionalData) { | ||
throw new Error("Failed to canonicalize additional data"); | ||
} | ||
const commitmentContent = canonicalize({ | ||
nonce, | ||
ciphertext, | ||
additionalData, | ||
}); | ||
if (!commitmentContent) { | ||
throw new Error("Failed to canonicalize commitment data"); | ||
} | ||
|
||
const isValidCommitment = sodium.crypto_auth_verify( | ||
sodium.from_base64(commitment), | ||
commitmentContent, | ||
key | ||
); | ||
if (!isValidCommitment) { | ||
throw new Error("Invalid commitment"); | ||
} | ||
|
||
const decryptedContent = sodium.crypto_aead_xchacha20poly1305_ietf_decrypt( | ||
null, | ||
sodium.from_base64(ciphertext), | ||
additionalData, | ||
sodium.from_base64(nonce), | ||
key | ||
); | ||
if (!decryptedContent) { | ||
throw new Error("Failed to decrypt locker"); | ||
} | ||
|
||
return sodium.to_string(decryptedContent); | ||
}; |
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,43 @@ | ||
import canonicalize from "canonicalize"; | ||
import * as sodium from "react-native-libsodium"; | ||
|
||
export const encryptLocker = ( | ||
content: string, | ||
clock: number, | ||
key: Uint8Array | ||
) => { | ||
const nonce = sodium.randombytes_buf( | ||
sodium.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES | ||
); | ||
const nonceString = sodium.to_base64(nonce); | ||
const additionalData = canonicalize({ clock }); | ||
if (!additionalData) { | ||
throw new Error("Failed to canonicalize additional data"); | ||
} | ||
const ciphertext = sodium.crypto_aead_xchacha20poly1305_ietf_encrypt( | ||
content, | ||
additionalData, | ||
null, | ||
nonce, | ||
key | ||
); | ||
const ciphertextString = sodium.to_base64(ciphertext); | ||
|
||
const commitmentContent = canonicalize({ | ||
nonce: nonceString, | ||
ciphertext: ciphertextString, | ||
additionalData, | ||
}); | ||
if (!commitmentContent) { | ||
throw new Error("Failed to canonicalize commitment data"); | ||
} | ||
|
||
const commitment = sodium.crypto_auth(commitmentContent, key); | ||
|
||
return { | ||
nonce: nonceString, | ||
ciphertext: ciphertextString, | ||
commitment: sodium.to_base64(commitment), | ||
clock, | ||
}; | ||
}; |
27 changes: 27 additions & 0 deletions
27
apps/server/prisma/migrations/20240602072616_add_locker/migration.sql
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,27 @@ | ||
/* | ||
Warnings: | ||
- You are about to drop the column `lala` on the `User` table. All the data in the column will be lost. | ||
*/ | ||
-- AlterTable | ||
ALTER TABLE "User" DROP COLUMN "lala"; | ||
|
||
-- CreateTable | ||
CREATE TABLE "UserLocker" ( | ||
"id" TEXT NOT NULL, | ||
"userId" TEXT NOT NULL, | ||
"clock" INTEGER NOT NULL, | ||
"ciphertext" TEXT NOT NULL, | ||
"nonce" TEXT NOT NULL, | ||
"commitment" TEXT NOT NULL, | ||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, | ||
|
||
CONSTRAINT "UserLocker_pkey" PRIMARY KEY ("id") | ||
); | ||
|
||
-- CreateIndex | ||
CREATE UNIQUE INDEX "UserLocker_userId_clock_key" ON "UserLocker"("userId", "clock"); | ||
|
||
-- AddForeignKey | ||
ALTER TABLE "UserLocker" ADD CONSTRAINT "UserLocker_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE; |
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,53 @@ | ||
import { Prisma } from "@prisma/client"; | ||
import { prisma } from "./prisma.js"; | ||
|
||
type Params = { | ||
userId: string; | ||
ciphertext: string; | ||
nonce: string; | ||
commitment: string; | ||
clock: number; | ||
}; | ||
|
||
export const createUserLocker = async ({ | ||
userId, | ||
ciphertext, | ||
clock, | ||
commitment, | ||
nonce, | ||
}: Params) => { | ||
return await prisma.$transaction( | ||
async (prisma) => { | ||
const userLocker = await prisma.userLocker.findFirst({ | ||
where: { | ||
userId, | ||
}, | ||
orderBy: { | ||
clock: "desc", | ||
}, | ||
}); | ||
|
||
console.log("userLocker", userLocker, clock); | ||
|
||
if (userLocker === null) { | ||
if (clock !== 0) { | ||
throw new Error("Invalid clock, expected 0"); | ||
} | ||
} else if (userLocker.clock + 1 !== clock) { | ||
throw new Error("Invalid clock"); | ||
} | ||
|
||
const locker = await prisma.userLocker.create({ | ||
data: { | ||
userId, | ||
ciphertext, | ||
nonce, | ||
commitment, | ||
clock, | ||
}, | ||
}); | ||
return { id: locker.id }; | ||
}, | ||
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable } | ||
); | ||
}; |
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,13 @@ | ||
import { prisma } from "./prisma.js"; | ||
|
||
export const getLatestUserLocker = async (userId: string) => { | ||
const locker = await prisma.userLocker.findFirst({ | ||
where: { | ||
userId, | ||
}, | ||
orderBy: { | ||
clock: "desc", | ||
}, | ||
}); | ||
return locker; | ||
}; |
Oops, something went wrong.