Skip to content
Draft
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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
"@vladfrangu/async_event_emitter": "^2.4.7",
"json-with-bigint": "^3.4.4",
"solid-js": "^1.9.14",
"stoat-api": "0.15.3",
"stoat-api": "git+https://github.com/Pecacheu/javascript-client-api#8a612098dd853dbaaad6ae03baf2af40c079818c",
"ulid": "^3.0.2"
},
"devDependencies": {
Expand Down
89 changes: 87 additions & 2 deletions src/classes/Channel.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
import { Accessor, Setter, batch, createSignal } from "solid-js";
import {
Accessor,
Setter,
batch,
createEffect,
createSignal,
on,
} from "solid-js";

import { ReactiveMap } from "@solid-primitives/map";
import type { ReactiveSet } from "@solid-primitives/set";
Expand All @@ -19,6 +26,8 @@ import { decodeTime, ulid } from "ulid";
import { ChannelCollection } from "../collections/index.js";
import { UserSlowmodes } from "../events/v1.js";
import { hydrate } from "../hydration/index.js";
import { APIMessageDec } from "../hydration/message.js";
import { EncryptError, decryptStr, encryptStr } from "../lib/e2ee.js";
import {
bitwiseAndEq,
calculatePermission,
Expand All @@ -27,7 +36,7 @@ import { Permission } from "../permissions/definitions.js";

import type { ChannelWebhook } from "./ChannelWebhook.js";
import type { File } from "./File.js";
import type { Message } from "./Message.js";
import { type Message, decodeMsg } from "./Message.js";
import type { Server } from "./Server.js";
import type { ServerMember } from "./ServerMember.js";
import type { User } from "./User.js";
Expand Down Expand Up @@ -60,6 +69,41 @@ export class Channel {
const [slowmode, setSlowmode] = createSignal<UserSlowmodes | undefined>();
this.userSlowmode = slowmode;
this.#setUserSlowmode = setSlowmode;

//Decrypt messages if key changes
let decRun = false;
createEffect(
on(
() => this.key,
(key) => {
if (!key || decRun) return;
decRun = true;
(async () => {
const decoded: [Message, string][] = [],
id = this.id;

//Decrypt asynchronously
for (const msg of this.#collection.client.messages.values())
if (msg.channelId === id)
try {
const cont = msg._rawContent();
if (cont != null) {
const dec = await decryptStr(key, cont);
if (dec != null) decoded.push([msg, dec]);
}
} catch (e) {
console.error(`Decrypt Msg ${this.id}`, e);
}

//Run update in batch
batch(() => {
for (const [msg, dec] of decoded) msg._setDecoded(dec);
});
decRun = false;
})();
},
),
);
}

/**
Expand Down Expand Up @@ -267,6 +311,23 @@ export class Channel {
return this.#collection.getUnderlyingObject(this.id).nsfw;
}

/**
* Whether messages are end-to-end encrypted
*/
get e2e(): boolean {
return this.#collection.getUnderlyingObject(this.id).e2e;
}

/**
* CryptoKey associated with this channel. Setting this enables decryption
*/
set key(k: CryptoKey) {
this.#collection.updateUnderlyingObject(this.id, "key", k);
}
get key(): CryptoKey | undefined {
return this.#collection.getUnderlyingObject(this.id).key;
}

/**
* ID of the last message sent in this channel
*/
Expand Down Expand Up @@ -545,6 +606,15 @@ export class Channel {
msg.flags |= 1;
}

let decoded: string | undefined;
if (this.e2e) {
if (!this.key) throw new EncryptError("no_key");
if (msg.content) {
decoded = msg.content;
msg.content = await encryptStr(this.key, msg.content);
}
}

const message = await this.#collection.client.api.post(
`/channels/${this.id as ""}/messages`,
msg,
Expand All @@ -555,6 +625,12 @@ export class Channel {
},
);

//Mark as already decoded
if (decoded) {
(message as APIMessageDec)._dec = decoded;
delete message.content;
}

return this.#collection.client.messages.getOrCreate(
message._id,
message,
Expand All @@ -573,6 +649,9 @@ export class Channel {
`/channels/${this.id as ""}/messages/${messageId as ""}`,
);

const key = this.key;
if (key) await decodeMsg(key, message);

return this.#collection.client.messages.getOrCreate(message._id, message);
}

Expand All @@ -596,6 +675,9 @@ export class Channel {
{ ...params },
)) as APIMessage[];

const key = this.key;
if (key) for (const m of messages) await decodeMsg(key, m);

return messages.map((message) =>
this.#collection.client.messages.getOrCreate(message._id, message),
);
Expand Down Expand Up @@ -625,6 +707,9 @@ export class Channel {
{ ...params, include_users: true },
)) as { messages: APIMessage[]; users: APIUser[]; members?: APIMember[] };

const key = this.key;
if (key) for (const m of data.messages) await decodeMsg(key, m);

return batch(() => ({
messages: data.messages.map((message) =>
this.#collection.client.messages.getOrCreate(message._id, message),
Expand Down
92 changes: 70 additions & 22 deletions src/classes/File.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { createSignal } from "solid-js";

import type { File as APIFile, Metadata } from "stoat-api";

import type { Client } from "../Client.js";
import { decrypt } from "../lib/e2ee.js";

/**
* Uploaded File
Expand Down Expand Up @@ -38,6 +41,12 @@ export class File {
*/
readonly size?: number;

/** Key's channel id, if encrypted */
readonly e2e_id: string;

#url;
#setUrl;

/**
* Construct File
* @param client Client
Expand All @@ -48,38 +57,77 @@ export class File {
file: (Pick<APIFile, "_id" | "tag" | "metadata"> & Partial<APIFile>) | File,
) {
this.#client = client;
if (file instanceof File) {

if ("id" in file) {
this.id = file.id;
this.tag = file.tag;
this.filename = file.filename;
this.metadata = file.metadata;
this.contentType = file.contentType;
this.size = file.size;
} else {
this.id = file._id;
this.tag = file.tag;
this.filename = file.filename;
this.metadata = file.metadata;
this.contentType = file.content_type;
this.size = file.size;
}

this.tag = file.tag;
this.filename = file.filename;
this.metadata = file.metadata;
this.size = file.size;
this.e2e_id = file.e2e_id!;

if (this.e2e_id && !("id" in file)) {
const [url, setUrl] = createSignal<string>();
this.#url = url;
this.#setUrl = setUrl;

if (this.filename) {
const extIdx = this.filename.indexOf("."),
ext = extIdx === -1 ? "" : this.filename.slice(extIdx),
mime = this.filename.slice(0, -ext.length);

//Detect meta type from mime
(this.contentType as string) = mime;
if (mime.startsWith("image/")) this.metadata.type = "Image";
else if (mime.startsWith("video/")) this.metadata.type = "Video";
else if (mime.startsWith("audio/")) this.metadata.type = "Audio";
else if (mime.startsWith("text/")) this.metadata.type = "Text";
this.filename = this.metadata.type.toLowerCase() + ext;
}
}
}

/**
* Direct URL to the file
*/
// get url(): string {
// if (!this.filename) return this.previewUrl;
//
// return `${this.#client.configuration?.features.autumn.url}/${this.tag}/${
// this.id
// }/${this.filename}`;
// }
/** Load encrypted file URL, if any. Call `unloadFile()` when finished */
async loadFile() {
if (!this.e2e_id) return;
const key = this.#client.channels.get(this.e2e_id)?.key;
if (key)
try {
const req = await fetch(this._rawUrl);
if (req.status !== 200) throw `HTTP Code ${req.status}`;
const buf = await decrypt(key, await req.arrayBuffer());
this.#setUrl!(
URL.createObjectURL(new Blob([buf], { type: this.contentType })),
);
} catch (e) {
console.error(`Decrypt File ${this.filename}`, e);
}
}

/** Unload file from memory */
unloadFile() {
if (!this.#url) return;
URL.revokeObjectURL(this.#url!()!);
this.#setUrl!();
}

get _rawUrl() {
return `${this.#client.configuration?.features.autumn.url}/${
this.tag
}/${this.id}/original`;
}

/**
* Preview URL for the file
*/
get previewUrl(): string {
if (this.e2e_id) return this.#url!() ?? "";
return `${this.#client.configuration?.features.autumn.url}/${
this.tag
}/${this.id}`;
Expand All @@ -89,9 +137,7 @@ export class File {
* Original download URL for the file
*/
get originalUrl(): string {
return `${this.#client.configuration?.features.autumn.url}/${
this.tag
}/${this.id}/original`;
return this.e2e_id ? (this.#url!() ?? "") : this._rawUrl;
}

/**
Expand Down Expand Up @@ -122,6 +168,8 @@ export class File {
* @returns Generated URL or nothing
*/
createFileURL(forceAnimation?: boolean): string | undefined {
if (this.e2e_id) return this.#url!() ?? "";

const autumn = this.#client.configuration?.features.autumn;
if (!autumn?.enabled) return;

Expand Down
35 changes: 33 additions & 2 deletions src/classes/Message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ import { decodeTime } from "ulid";

import type { Client } from "../Client.js";
import type { MessageCollection } from "../collections/MessageCollection.js";
import { MessageFlags } from "../hydration/message.js";
import { APIMessageDec, MessageFlags } from "../hydration/message.js";
import { EncryptError, decryptStr, encryptStr } from "../lib/e2ee.js";

import type { Channel } from "./Channel.js";
import { File } from "./File.js";
Expand All @@ -22,6 +23,20 @@ import { ServerRole } from "./ServerRole.js";
import type { SystemMessage } from "./SystemMessage.js";
import type { User } from "./User.js";

/** Load decrypted payload into APIMessage */
export async function decodeMsg(
cliOrKey: Client | CryptoKey,
msg: Partial<APIMessageDec>,
) {
if (!msg.content) return;
const key =
"usages" in cliOrKey ? cliOrKey : cliOrKey.channels.get(msg.channel!)?.key;
if (key) {
msg._dec = await decryptStr(key, msg.content!);
delete msg.content;
}
}

/**
* Message Class
*/
Expand All @@ -39,6 +54,15 @@ export class Message {
this.id = id;
}

_rawContent() {
return this.#collection.getUnderlyingObject(this.id).content;
}

_setDecoded(dec: string) {
this.#collection.updateUnderlyingObject(this.id, "_dec", dec);
this.#collection.updateUnderlyingObject(this.id, "content", undefined);
}

/**
* Whether this object exists
*/
Expand Down Expand Up @@ -134,7 +158,8 @@ export class Message {
* Content
*/
get content(): string {
return this.#collection.getUnderlyingObject(this.id).content ?? "";
const obj = this.#collection.getUnderlyingObject(this.id);
return (this.channel?.e2e ? obj._dec : obj.content) ?? "";
}

/**
Expand Down Expand Up @@ -330,6 +355,12 @@ export class Message {
* @param data Message edit route data
*/
async edit(data: DataEditMessage): Promise<APIMessage> {
const chan = this.channel;
if (chan?.e2e) {
if (!chan.key) throw new EncryptError("no_key");
if (data.content) data.content = await encryptStr(chan.key, data.content);
}

return await this.#collection.client.api.patch(
`/channels/${this.channelId as ""}/messages/${this.id as ""}`,
data,
Expand Down
3 changes: 2 additions & 1 deletion src/collections/MessageCollection.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { Message as APIMessage } from "stoat-api";

import { Message } from "../classes/Message.js";
import { Message, decodeMsg } from "../classes/Message.js";
import type { HydratedMessage } from "../hydration/message.js";

import { ClassCollection } from "./Collection.js";
Expand All @@ -26,6 +26,7 @@ export class MessageCollection extends ClassCollection<
`/channels/${channelId as ""}/messages/${messageId as ""}`,
);

await decodeMsg(this.client, data);
return this.getOrCreate(data._id, data, false);
}

Expand Down
Loading
Loading