Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

fix(security): remove raw encryption key from team invite URLs

Louis Beaumont403dc8d10dd9
diff --git a/apps/screenpipe-app-tauri/components/settings/team-section.tsx b/apps/screenpipe-app-tauri/components/settings/team-section.tsx
index 949e09c3a..31dbb59cc 100644
--- a/apps/screenpipe-app-tauri/components/settings/team-section.tsx
+++ b/apps/screenpipe-app-tauri/components/settings/team-section.tsx
@@ -53,6 +53,12 @@ export function TeamSection() {
const [confirmDelete, setConfirmDelete] = useState(false);
const [inviteEmail, setInviteEmail] = useState("");
const [sendingInvite, setSendingInvite] = useState(false);
+ const [passphraseInput, setPassphraseInput] = useState("");
+ const [pendingJoin, setPendingJoin] = useState<{
+ teamId: string;
+ claimToken: string;
+ inviteToken?: string;
+ } | null>(null);
const handleRemoveFilterItem = async (config: TeamConfig, filterToRemove: string) => {
const currentFilters = (config.value as { filters?: string[] })?.filters || [];
@@ -90,16 +96,29 @@ export function TeamSection() {
try {
const parsed = new URL(url);
const teamId = parsed.searchParams.get("team_id");
- const key = parsed.searchParams.get("key");
const inviteToken = parsed.searchParams.get("invite_token");
- if (teamId && key) {
- setJoining(true);
- await team.joinTeam(
+ const claimToken = parsed.searchParams.get("claim");
+ const legacyKey = parsed.searchParams.get("key");
+
+ if (teamId && claimToken) {
+ // new secure flow: need passphrase from user
+ setPendingJoin({
teamId,
- decodeURIComponent(key),
- inviteToken ? decodeURIComponent(inviteToken) : undefined
- );
- posthog.capture("team_joined", { source: "deep_link" });
+ claimToken: decodeURIComponent(claimToken),
+ inviteToken: inviteToken ? decodeURIComponent(inviteToken) : undefined,
+ });
+ toast({
+ title: "enter passphrase to join team",
+ description: "ask the admin for the passphrase they received when creating the invite",
+ });
+ } else if (teamId && legacyKey) {
+ // legacy flow: raw key in URL (old invite links)
+ setJoining(true);
+ await team.joinTeam(teamId, {
+ legacyBase64Key: decodeURIComponent(legacyKey),
+ inviteToken: inviteToken ? decodeURIComponent(inviteToken) : undefined,
+ });
+ posthog.capture("team_joined", { source: "deep_link_legacy" });
toast({
title: "joined team!",
description: "you are now a team member",
@@ -147,21 +166,61 @@ export function TeamSection() {
const handleJoinFromLink = async () => {
if (!inviteInput.trim()) return;
- setJoining(true);
try {
const parsed = new URL(inviteInput.trim());
const teamId = parsed.searchParams.get("team_id");
- const key = parsed.searchParams.get("key");
const inviteToken = parsed.searchParams.get("invite_token");
- if (!teamId || !key) throw new Error("invalid invite link — must contain team_id and key");
- await team.joinTeam(
- teamId,
- decodeURIComponent(key),
- inviteToken ? decodeURIComponent(inviteToken) : undefined
- );
- posthog.capture("team_joined", { source: "invite_link" });
- setInviteInput("");
- setShowJoinInput(false);
+ const claimToken = parsed.searchParams.get("claim");
+ const legacyKey = parsed.searchParams.get("key");
+
+ if (!teamId) throw new Error("invalid invite link — missing team_id");
+
+ if (claimToken) {
+ // new secure flow: prompt for passphrase
+ setPendingJoin({
+ teamId,
+ claimToken: decodeURIComponent(claimToken),
+ inviteToken: inviteToken ? decodeURIComponent(inviteToken) : undefined,
+ });
+ setInviteInput("");
+ setShowJoinInput(false);
+ } else if (legacyKey) {
+ // legacy flow: raw key in URL
+ setJoining(true);
+ await team.joinTeam(teamId, {
+ legacyBase64Key: decodeURIComponent(legacyKey),
+ inviteToken: inviteToken ? decodeURIComponent(inviteToken) : undefined,
+ });
+ posthog.capture("team_joined", { source: "invite_link_legacy" });
+ setInviteInput("");
+ setShowJoinInput(false);
+ toast({ title: "joined team!" });
+ } else {
+ throw new Error("invalid invite link — missing claim or key parameter");
+ }
+ } catch (err: any) {
+ toast({
+ title: "failed to join team",
+ description: err.message,
+ variant: "destructive",
+ });
+ } finally {
+ setJoining(false);
+ }
+ };
+
+ const handleJoinWithPassphrase = async () => {
+ if (!pendingJoin || !passphraseInput.trim()) return;
+ setJoining(true);
+ try {
+ await team.joinTeam(pendingJoin.teamId, {
+ claimToken: pendingJoin.claimToken,
+ passphrase: passphraseInput.trim().toLowerCase(),
+ inviteToken: pendingJoin.inviteToken,
+ });
+ posthog.capture("team_joined", { source: "secure_invite" });
+ setPendingJoin(null);
+ setPassphraseInput("");
toast({ title: "joined team!" });
} catch (err: any) {
toast({
@@ -296,6 +355,65 @@ export function TeamSection() {
);
}
+ // passphrase prompt for joining (shown when user clicked a secure invite link)
+ if (pendingJoin) {
+ return (
+ <div className="space-y-6">
+ <div>
+ <h1 className="text-2xl font-bold tracking-tight text-foreground">
+ Join Team
+ </h1>
+ <p className="text-sm text-muted-foreground mt-0.5">
+ enter the passphrase from your team admin to complete joining
+ </p>
+ </div>
+
+ <Card className="p-6">
+ <div className="flex items-start gap-3 mb-4">
+ <Lock className="h-5 w-5 text-muted-foreground mt-0.5" />
+ <div>
+ <h3 className="text-sm font-medium">passphrase required</h3>
+ <p className="text-xs text-muted-foreground mt-1">
+ your admin shared a passphrase separately (verbally, Signal, etc.)
+ — enter it below to decrypt the team encryption key
+ </p>
+ </div>
+ </div>
+ <div className="flex gap-2">
+ <Input
+ placeholder="e.g. abc23def"
+ value={passphraseInput}
+ onChange={(e) => setPassphraseInput(e.target.value)}
+ onKeyDown={(e) => e.key === "Enter" && handleJoinWithPassphrase()}
+ className="font-mono text-lg tracking-widest max-w-xs"
+ autoFocus
+ />
+ <Button
+ onClick={handleJoinWithPassphrase}
+ disabled={joining || !passphraseInput.trim()}
+ >
+ {joining ? (
+ <Loader2 className="h-4 w-4 animate-spin mr-1.5" />
+ ) : (
+ <Lock className="h-4 w-4 mr-1.5" />
+ )}
+ join
+ </Button>
+ <Button
+ variant="ghost"
+ onClick={() => {
+ setPendingJoin(null);
+ setPassphraseInput("");
+ }}
+ >
+ cancel
+ </Button>
+ </div>
+ </Card>
+ </div>
+ );
+ }
+
// no team yet
if (!team.team) {
return (
@@ -346,7 +464,7 @@ export function TeamSection() {
{showJoinInput ? (
<div className="flex gap-2">
<Input
- placeholder="screenpipe://join-team?team_id=...&key=..."
+ placeholder="screenpipe://join-team?team_id=...&claim=..."
value={inviteInput}
onChange={(e) => setInviteInput(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && handleJoinFromLink()}
@@ -429,9 +547,8 @@ export function TeamSection() {
invite link
</h3>
</div>
- <p className="text-xs text-muted-foreground mb-2 flex items-center gap-1">
- <AlertTriangle className="h-3 w-3" />
- contains your encryption key — share only via secure channel
+ <p className="text-xs text-muted-foreground mb-2">
+ share this link with your teammate — it does not contain the encryption key
</p>
<div className="flex gap-2 items-stretch">
<Input
@@ -447,6 +564,33 @@ export function TeamSection() {
)}
</Button>
</div>
+ {team.invitePassphrase && (
+ <div className="mt-3 p-3 rounded-md bg-muted/50 border">
+ <p className="text-xs font-medium mb-1 flex items-center gap-1">
+ <Lock className="h-3 w-3" />
+ passphrase (share separately — verbally or via secure channel)
+ </p>
+ <div className="flex items-center gap-2">
+ <code className="text-lg font-bold tracking-widest select-all">
+ {team.invitePassphrase}
+ </code>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-7"
+ onClick={async () => {
+ await navigator.clipboard.writeText(team.invitePassphrase!);
+ toast({ title: "passphrase copied" });
+ }}
+ >
+ <Copy className="h-3 w-3" />
+ </Button>
+ </div>
+ <p className="text-[10px] text-muted-foreground mt-1">
+ your teammate will need this to decrypt the team encryption key
+ </p>
+ </div>
+ )}
</Card>
)}
diff --git a/apps/screenpipe-app-tauri/lib/__tests__/team-api-contract.test.ts b/apps/screenpipe-app-tauri/lib/__tests__/team-api-contract.test.ts
index 9b32bf731..cef1a5ac3 100644
--- a/apps/screenpipe-app-tauri/lib/__tests__/team-api-contract.test.ts
+++ b/apps/screenpipe-app-tauri/lib/__tests__/team-api-contract.test.ts
@@ -9,6 +9,9 @@ import {
importTeamKey,
encryptConfig,
decryptConfig,
+ generatePassphrase,
+ wrapKeyWithPassphrase,
+ unwrapKeyWithPassphrase,
} from "../team-crypto";
/**
@@ -181,11 +184,10 @@ describe("team API contract", () => {
});
});
- describe("invite link E2E flow", () => {
- it("admin creates team → generates invite → member joins → decrypts configs", async () => {
+ describe("secure invite E2E flow", () => {
+ it("admin wraps key → uploads claim → member fetches claim → unwraps → decrypts configs", async () => {
// Step 1: admin creates team and key
const adminKey = await generateTeamKey();
- const keyBase64 = await exportTeamKey(adminKey);
// Step 2: admin pushes config (encrypted)
const pipeConfig = {
@@ -195,21 +197,34 @@ describe("team API contract", () => {
};
const encryptedForBackend = await encryptConfig(pipeConfig, adminKey);
- // Step 3: admin generates invite link
- const inviteLink = `screenpipe://join-team?team_id=${MOCK_TEAM_ID}&key=${encodeURIComponent(keyBase64)}`;
+ // Step 3: admin wraps key with passphrase
+ const passphrase = generatePassphrase();
+ const wrapped = await wrapKeyWithPassphrase(adminKey, passphrase);
+
+ // Step 4: admin uploads wrapped blob to server (POST /api/team/key-claim)
+ // server returns claim_token
+ const mockClaimToken = "claim-abc-123";
- // Step 4: member receives link, extracts key
+ // Step 5: invite link contains NO key material
+ const inviteLink = `screenpipe://join-team?team_id=${MOCK_TEAM_ID}&invite_token=tok-xyz&claim=${mockClaimToken}`;
const url = new URL(inviteLink);
- const teamId = url.searchParams.get("team_id");
- const keyParam = url.searchParams.get("key");
- expect(teamId).toBe(MOCK_TEAM_ID);
- expect(keyParam).toBeDefined();
+ expect(url.searchParams.get("team_id")).toBe(MOCK_TEAM_ID);
+ expect(url.searchParams.get("claim")).toBe(mockClaimToken);
+ expect(url.searchParams.has("key")).toBe(false); // NO raw key in URL
- // Step 5: member imports key
- const memberKey = await importTeamKey(decodeURIComponent(keyParam!));
+ // Step 6: member fetches wrapped blob from server (GET /api/team/key-claim/:token)
+ // server returns: { encrypted_key, salt, nonce }
+
+ // Step 7: member unwraps with passphrase (shared out-of-band)
+ const memberKey = await unwrapKeyWithPassphrase(
+ wrapped.encrypted_key,
+ wrapped.salt,
+ wrapped.nonce,
+ passphrase
+ );
- // Step 6: member fetches configs from backend and decrypts
+ // Step 8: member decrypts configs
const decrypted = await decryptConfig(
encryptedForBackend.value_encrypted,
encryptedForBackend.nonce,
@@ -219,6 +234,29 @@ describe("team API contract", () => {
});
});
+ describe("legacy invite link E2E flow (backwards compat)", () => {
+ it("old invite links with raw key still work", async () => {
+ const adminKey = await generateTeamKey();
+ const keyBase64 = await exportTeamKey(adminKey);
+
+ const pipeConfig = { pipe_id: "legacy-pipe", enabled: true };
+ const encrypted = await encryptConfig(pipeConfig, adminKey);
+
+ // old-style link with key= param
+ const inviteLink = `screenpipe://join-team?team_id=${MOCK_TEAM_ID}&key=${encodeURIComponent(keyBase64)}`;
+ const url = new URL(inviteLink);
+ const keyParam = url.searchParams.get("key");
+
+ const memberKey = await importTeamKey(decodeURIComponent(keyParam!));
+ const decrypted = await decryptConfig(
+ encrypted.value_encrypted,
+ encrypted.nonce,
+ memberKey
+ );
+ expect(decrypted).toEqual(pipeConfig);
+ });
+ });
+
describe("permission enforcement", () => {
function checkPermission(role: string, scope: string, userId: string): boolean {
if (scope === "team") return role === "admin";
diff --git a/apps/screenpipe-app-tauri/lib/__tests__/team-crypto.test.ts b/apps/screenpipe-app-tauri/lib/__tests__/team-crypto.test.ts
index 62331da96..f746082bb 100644
--- a/apps/screenpipe-app-tauri/lib/__tests__/team-crypto.test.ts
+++ b/apps/screenpipe-app-tauri/lib/__tests__/team-crypto.test.ts
@@ -9,6 +9,9 @@ import {
importTeamKey,
encryptConfig,
decryptConfig,
+ generatePassphrase,
+ wrapKeyWithPassphrase,
+ unwrapKeyWithPassphrase,
} from "../team-crypto";
describe("team-crypto", () => {
@@ -170,7 +173,7 @@ describe("team-crypto", () => {
});
});
- describe("invite link key flow", () => {
+ describe("invite link key flow (legacy)", () => {
it("should simulate full invite link flow: generate → export → URL → import → decrypt", async () => {
// admin creates team and generates key
const adminKey = await generateTeamKey();
@@ -202,4 +205,82 @@ describe("team-crypto", () => {
expect(decrypted).toEqual(pipeConfig);
});
});
+
+ describe("passphrase-based key wrapping", () => {
+ it("should generate 8-character passphrases", () => {
+ const passphrase = generatePassphrase();
+ expect(passphrase.length).toBe(8);
+ expect(/^[a-z0-9]+$/.test(passphrase)).toBe(true);
+ });
+
+ it("should generate unique passphrases", () => {
+ const p1 = generatePassphrase();
+ const p2 = generatePassphrase();
+ expect(p1).not.toBe(p2);
+ });
+
+ it("should round-trip wrap → unwrap with correct passphrase", async () => {
+ const teamKey = await generateTeamKey();
+ const passphrase = generatePassphrase();
+
+ const wrapped = await wrapKeyWithPassphrase(teamKey, passphrase);
+ expect(wrapped.encrypted_key).toBeDefined();
+ expect(wrapped.salt).toBeDefined();
+ expect(wrapped.nonce).toBeDefined();
+
+ const unwrapped = await unwrapKeyWithPassphrase(
+ wrapped.encrypted_key,
+ wrapped.salt,
+ wrapped.nonce,
+ passphrase
+ );
+
+ // verify same key material
+ const raw1 = new Uint8Array(await crypto.subtle.exportKey("raw", teamKey));
+ const raw2 = new Uint8Array(await crypto.subtle.exportKey("raw", unwrapped));
+ expect(raw1).toEqual(raw2);
+ });
+
+ it("should fail to unwrap with wrong passphrase", async () => {
+ const teamKey = await generateTeamKey();
+ const wrapped = await wrapKeyWithPassphrase(teamKey, "correctpass");
+
+ await expect(
+ unwrapKeyWithPassphrase(
+ wrapped.encrypted_key,
+ wrapped.salt,
+ wrapped.nonce,
+ "wrongpass"
+ )
+ ).rejects.toThrow();
+ });
+
+ it("should simulate full secure invite flow: wrap → claim → unwrap → decrypt", async () => {
+ // admin generates team key and encrypts a config
+ const adminKey = await generateTeamKey();
+ const pipeConfig = { pipe_id: "compliance", enabled: true };
+ const encrypted = await encryptConfig(pipeConfig, adminKey);
+
+ // admin wraps key with passphrase for invite
+ const passphrase = generatePassphrase();
+ const wrapped = await wrapKeyWithPassphrase(adminKey, passphrase);
+
+ // simulate: wrapped blob stored on server, claim token in invite URL
+ // member fetches blob from server, unwraps with passphrase
+ const memberKey = await unwrapKeyWithPassphrase(
+ wrapped.encrypted_key,
+ wrapped.salt,
+ wrapped.nonce,
+ passphrase
+ );
+
+ // member decrypts config
+ const decrypted = await decryptConfig(
+ encrypted.value_encrypted,
+ encrypted.nonce,
+ memberKey
+ );
+ expect(decrypted).toEqual(pipeConfig);
+ });
+ });
});
diff --git a/apps/screenpipe-app-tauri/lib/hooks/use-team.ts b/apps/screenpipe-app-tauri/lib/hooks/use-team.ts
index 053fa98b1..b627c03d2 100644
--- a/apps/screenpipe-app-tauri/lib/hooks/use-team.ts
+++ b/apps/screenpipe-app-tauri/lib/hooks/use-team.ts
@@ -10,6 +10,9 @@ import {
importTeamKey,
encryptConfig,
decryptConfig,
+ generatePassphrase,
+ wrapKeyWithPassphrase,
+ unwrapKeyWithPassphrase,
} from "../team-crypto";
const API = "https://screenpi.pe/api/team";
@@ -50,6 +53,7 @@ interface TeamState {
members: TeamMember[];
configs: TeamConfig[];
inviteLink: string | null;
+ invitePassphrase: string | null;
loading: boolean;
error: string | null;
}
@@ -99,6 +103,7 @@ export function useTeam() {
members: [],
configs: [],
inviteLink: null,
+ invitePassphrase: null,
loading: true,
error: null,
});
@@ -145,11 +150,14 @@ export function useTeam() {
teamKeyRef.current = key;
// generate invite link if admin and has key
- // the invite link contains the encryption key + a server-generated invite token
- // email invites use a separate token (no key sent to server)
+ // the invite link NO LONGER contains the raw encryption key
+ // instead: key is wrapped with a passphrase, uploaded to server as a one-time claim
+ // admin shares passphrase separately via secure channel
let inviteLink: string | null = null;
+ let invitePassphrase: string | null = null;
if (data.role === "admin" && key) {
try {
+ // 1. generate invite token
const tokenRes = await fetch(`${API}/invite`, {
method: "POST",
headers: headers(),
@@ -160,13 +168,28 @@ export function useTeam() {
});
if (tokenRes.ok) {
const tokenData = await tokenRes.json();
- const b64Key = await exportTeamKey(key);
- inviteLink = `screenpipe://join-team?team_id=${data.team.id}&key=${encodeURIComponent(b64Key)}&invite_token=${tokenData.invite_token}`;
+
+ // 2. wrap key with passphrase and upload to server
+ const passphrase = generatePassphrase();
+ const wrapped = await wrapKeyWithPassphrase(key, passphrase);
+
+ const claimRes = await fetch(`${API}/key-claim`, {
+ method: "POST",
+ headers: headers(),
+ body: JSON.stringify({
+ invite_token: tokenData.invite_token,
+ ...wrapped,
+ }),
+ });
+
+ if (claimRes.ok) {
+ const claimData = await claimRes.json();
+ inviteLink = `screenpipe://join-team?team_id=${data.team.id}&invite_token=${tokenData.invite_token}&claim=${claimData.claim_token}`;
+ invitePassphrase = passphrase;
+ }
}
} catch {
- // fall back to link without token (won't work for joining, but shows the key)
- const b64Key = await exportTeamKey(key);
- inviteLink = `screenpipe://join-team?team_id=${data.team.id}&key=${encodeURIComponent(b64Key)}`;
+ // invite generation failed — user can retry
}
}
@@ -175,6 +198,7 @@ export function useTeam() {
team: data.team,
role: data.role,
inviteLink,
+ invitePassphrase,
loading: false,
}));
@@ -264,13 +288,51 @@ export function useTeam() {
[token, fetchTeam]
);
- // join team from invite link (contains key) or from email invite (token only, key shared separately)
+ // join team via:
+ // 1. new flow: claim token + passphrase (key fetched from server, unwrapped locally)
+ // 2. legacy flow: raw base64 key in URL (backwards compat for old invite links)
const joinTeam = useCallback(
- async (teamId: string, base64Key: string, inviteToken?: string) => {
+ async (
+ teamId: string,
+ opts: {
+ claimToken?: string;
+ passphrase?: string;
+ legacyBase64Key?: string;
+ inviteToken?: string;
+ }
+ ) => {
if (!token) throw new Error("not logged in");
- // import and store the key
- const key = await importTeamKey(base64Key);
+ let key: CryptoKey;
+
+ if (opts.legacyBase64Key) {
+ // legacy flow: raw key in URL (old invite links)
+ key = await importTeamKey(opts.legacyBase64Key);
+ } else if (opts.claimToken && opts.passphrase) {
+ // new flow: fetch wrapped key from server, unwrap with passphrase
+ const claimRes = await fetch(
+ `${API}/key-claim/${encodeURIComponent(opts.claimToken)}`,
+ { headers: headers() }
+ );
+ if (!claimRes.ok) {
+ const err = await claimRes.json();
+ throw new Error(err.error || "failed to claim encryption key");
+ }
+ const claimData = await claimRes.json();
+ try {
+ key = await unwrapKeyWithPassphrase(
+ claimData.encrypted_key,
+ claimData.salt,
+ claimData.nonce,
+ opts.passphrase
+ );
+ } catch {
+ throw new Error("incorrect passphrase — could not decrypt team key");
+ }
+ } else {
+ throw new Error("invite link is missing key information");
+ }
+
await saveTeamKeyToStore(teamId, key);
teamKeyRef.current = key;
@@ -279,7 +341,7 @@ export function useTeam() {
headers: headers(),
body: JSON.stringify({
team_id: teamId,
- invite_token: inviteToken || "direct",
+ invite_token: opts.inviteToken || "direct",
}),
});
if (!res.ok) {
@@ -316,6 +378,7 @@ export function useTeam() {
members: [],
configs: [],
inviteLink: null,
+ invitePassphrase: null,
loading: false,
error: null,
});
@@ -344,6 +407,7 @@ export function useTeam() {
members: [],
configs: [],
inviteLink: null,
+ invitePassphrase: null,
loading: false,
error: null,
});
diff --git a/apps/screenpipe-app-tauri/lib/team-crypto.ts b/apps/screenpipe-app-tauri/lib/team-crypto.ts
index cbc3d06c9..3d436e177 100644
--- a/apps/screenpipe-app-tauri/lib/team-crypto.ts
+++ b/apps/screenpipe-app-tauri/lib/team-crypto.ts
@@ -68,3 +68,91 @@ export async function decryptConfig(
);
return JSON.parse(new TextDecoder().decode(plaintext));
}
+
+// --- Passphrase-based key wrapping for secure invite flow ---
+
+const PBKDF2_ITERATIONS = 600_000;
+
+/** Generate a random 8-character alphanumeric passphrase */
+export function generatePassphrase(): string {
+ const chars = "abcdefghijkmnpqrstuvwxyz23456789"; // no ambiguous: 0/O, 1/l
+ const arr = crypto.getRandomValues(new Uint8Array(8));
+ return Array.from(arr, (b) => chars[b % chars.length]).join("");
+}
+
+/** Wrap a team key with a passphrase using PBKDF2 + AES-GCM */
+export async function wrapKeyWithPassphrase(
+ teamKey: CryptoKey,
+ passphrase: string
+): Promise<{ encrypted_key: string; salt: string; nonce: string }> {
+ const salt = crypto.getRandomValues(new Uint8Array(16));
+ const nonce = crypto.getRandomValues(new Uint8Array(12));
+
+ const wrappingKey = await deriveKeyFromPassphrase(passphrase, salt);
+ const rawKey = await crypto.subtle.exportKey("raw", teamKey);
+
+ const ciphertext = await crypto.subtle.encrypt(
+ { name: "AES-GCM", iv: nonce },
+ wrappingKey,
+ rawKey
+ );
+
+ return {
+ encrypted_key: btoa(String.fromCharCode(...new Uint8Array(ciphertext))),
+ salt: btoa(String.fromCharCode(...salt)),
+ nonce: btoa(String.fromCharCode(...nonce)),
+ };
+}
+
+/** Unwrap a team key using passphrase */
+export async function unwrapKeyWithPassphrase(
+ encrypted_key: string,
+ salt: string,
+ nonce: string,
+ passphrase: string
+): Promise<CryptoKey> {
+ const saltBytes = Uint8Array.from(atob(salt), (c) => c.charCodeAt(0));
+ const nonceBytes = Uint8Array.from(atob(nonce), (c) => c.charCodeAt(0));
+ const ciphertextBytes = Uint8Array.from(atob(encrypted_key), (c) =>
+ c.charCodeAt(0)
+ );
+
+ const wrappingKey = await deriveKeyFromPassphrase(passphrase, saltBytes);
+
+ const rawKey = await crypto.subtle.decrypt(
+ { name: "AES-GCM", iv: nonceBytes },
+ wrappingKey,
+ ciphertextBytes
+ );
+
+ return crypto.subtle.importKey("raw", rawKey, { name: "AES-GCM" }, true, [
+ "encrypt",
+ "decrypt",
+ ]);
+}
+
+async function deriveKeyFromPassphrase(
+ passphrase: string,
+ salt: Uint8Array
+): Promise<CryptoKey> {
+ const keyMaterial = await crypto.subtle.importKey(
+ "raw",
+ new TextEncoder().encode(passphrase),
+ "PBKDF2",
+ false,
+ ["deriveKey"]
+ );
+
+ return crypto.subtle.deriveKey(
+ {
+ name: "PBKDF2",
+ salt,
+ iterations: PBKDF2_ITERATIONS,
+ hash: "SHA-256",
+ },
+ keyMaterial,
+ { name: "AES-GCM", length: 256 },
+ false,
+ ["encrypt", "decrypt"]
+ );
+}