korero-chat 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,72 @@
1
+ import { ed25519 } from "@noble/curves/ed25519.js";
2
+ const encoder = new TextEncoder();
3
+ const header = encoder.encode("KORERO-IDENTITY-1");
4
+ const pkcs8Header = [0x30, 0x51, 2, 1, 1, 0x30, 5, 6, 3, 0x2b, 0x65, 0x70, 4, 0x22, 4, 0x20];
5
+ export function encodeBase64Url(bytes) {
6
+ const data = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
7
+ let binary = "";
8
+ for (let offset = 0; offset < data.length; offset += 8192) {
9
+ binary += String.fromCharCode(...data.subarray(offset, offset + 8192));
10
+ }
11
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
12
+ }
13
+ export function decodeBase64Url(value) {
14
+ return Uint8Array.from(atob(value.replace(/-/g, "+").replace(/_/g, "/")), (character) => character.charCodeAt(0));
15
+ }
16
+ function checkEnvelope(pkcs8) {
17
+ if (pkcs8.length !== 83 || !pkcs8Header.every((byte, index) => byte === pkcs8[index]) ||
18
+ pkcs8[48] !== 0x81 || pkcs8[49] !== 0x21 || pkcs8[50] !== 0)
19
+ throw new Error("Invalid Korero.chat identity key.");
20
+ }
21
+ export function identitySeed(privateKey) {
22
+ const pkcs8 = decodeBase64Url(privateKey);
23
+ checkEnvelope(pkcs8);
24
+ return pkcs8.slice(16, 48);
25
+ }
26
+ export async function generateIdentity() {
27
+ const seed = crypto.getRandomValues(new Uint8Array(32));
28
+ const publicKey = ed25519.getPublicKey(seed);
29
+ // Use the same PKCS#8 envelope as the native client.
30
+ const pkcs8 = Uint8Array.of(...pkcs8Header, ...seed, 0x81, 0x21, 0, ...publicKey);
31
+ return { privateKey: encodeBase64Url(pkcs8), publicKey: encodeBase64Url(publicKey) };
32
+ }
33
+ function unpack(pkcs8) {
34
+ checkEnvelope(pkcs8);
35
+ const seed = pkcs8.slice(16, 48);
36
+ const publicKey = encodeBase64Url(ed25519.getPublicKey(seed));
37
+ if (publicKey !== encodeBase64Url(pkcs8.slice(51)))
38
+ throw new Error("Invalid Korero.chat identity key.");
39
+ return { seed, publicKey };
40
+ }
41
+ export function identityFromPrivateKey(privateKey) {
42
+ const { publicKey } = unpack(decodeBase64Url(privateKey));
43
+ return { privateKey, publicKey };
44
+ }
45
+ async function wrappingKey(passphrase, salt) {
46
+ if (Array.from(passphrase).length < 12)
47
+ throw new Error("Use a passphrase of at least 12 characters.");
48
+ const base = await crypto.subtle.importKey("raw", encoder.encode(passphrase), "PBKDF2", false, ["deriveKey"]);
49
+ return crypto.subtle.deriveKey({ name: "PBKDF2", salt, iterations: 600000, hash: "SHA-256" }, base, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]);
50
+ }
51
+ export async function importIdentity(blob, passphrase) {
52
+ const bytes = decodeBase64Url(blob.trim());
53
+ const offset = header.length;
54
+ if (bytes.length !== offset + 16 + 12 + 83 + 16 || !header.every((byte, index) => bytes[index] === byte)) {
55
+ throw new Error("Invalid Korero.chat identity export.");
56
+ }
57
+ const key = await wrappingKey(passphrase, bytes.slice(offset, offset + 16));
58
+ const pkcs8 = await crypto.subtle.decrypt({ name: "AES-GCM", iv: bytes.slice(offset + 16, offset + 28), additionalData: header }, key, bytes.slice(offset + 28)).catch(() => { throw new Error("Incorrect passphrase or damaged identity export."); });
59
+ const { publicKey } = unpack(new Uint8Array(pkcs8));
60
+ return { privateKey: encodeBase64Url(pkcs8), publicKey };
61
+ }
62
+ export async function exportIdentity(privateKey, passphrase) {
63
+ const salt = crypto.getRandomValues(new Uint8Array(16));
64
+ const iv = crypto.getRandomValues(new Uint8Array(12));
65
+ const key = await wrappingKey(passphrase, salt);
66
+ const sealed = await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData: header }, key, decodeBase64Url(privateKey));
67
+ return encodeBase64Url(Uint8Array.of(...header, ...salt, ...iv, ...new Uint8Array(sealed)));
68
+ }
69
+ export async function signIdentity(identity, transcript) {
70
+ const { seed } = unpack(decodeBase64Url(identity.privateKey));
71
+ return encodeBase64Url(ed25519.sign(encoder.encode(JSON.stringify(transcript)), seed));
72
+ }
@@ -0,0 +1,15 @@
1
+ export { Channel, ChannelMessage } from "./channel.js";
2
+ export type { ChannelOptions, MessageContent } from "./channel.js";
3
+ export { KoreroClient } from "./session.js";
4
+ export type { ClientEvents, ConnectOptions, SessionOptions, SessionMedia, SessionMediaAdapter } from "./session.js";
5
+ export { createApi, serverApi } from "./http.js";
6
+ export type { AccountPage, ApiResult, AttachmentUpload, AuditPage, ChannelOrder, ChannelPermission, ChannelPermissionTable, ConnectionDetails, Invitation, Permission, RoleDefinition, ServerCapabilities, ServerPreferences, } from "./http.js";
7
+ export { serverOrigin, webTransport } from "./transport.js";
8
+ export type { ServerSocket, Transport } from "./transport.js";
9
+ export { messageFrom, requestError } from "./errors.js";
10
+ export { generateIdentity, importIdentity, exportIdentity, identityFromPrivateKey, encodeBase64Url, decodeBase64Url } from "./identity.js";
11
+ export type { DeviceIdentity } from "./identity.js";
12
+ export type { IdentityAction, IdentityAuthentication } from "./auth.js";
13
+ export { directConversation, encodeDirectContent, decodeDirectContent } from "./direct-crypto.js";
14
+ export type { DirectCursor, DirectPacket, DirectPage, DirectPeer } from "./direct-crypto.js";
15
+ export * from "./types.js";
package/dist/index.js ADDED
@@ -0,0 +1,8 @@
1
+ export { Channel, ChannelMessage } from "./channel.js";
2
+ export { KoreroClient } from "./session.js";
3
+ export { createApi, serverApi } from "./http.js";
4
+ export { serverOrigin, webTransport } from "./transport.js";
5
+ export { messageFrom, requestError } from "./errors.js";
6
+ export { generateIdentity, importIdentity, exportIdentity, identityFromPrivateKey, encodeBase64Url, decodeBase64Url } from "./identity.js";
7
+ export { directConversation, encodeDirectContent, decodeDirectContent } from "./direct-crypto.js";
8
+ export * from "./types.js";
@@ -0,0 +1,143 @@
1
+ import { type DirectMessage, type DirectMessageChange, type DirectOperation, type MemberRequest, type Poke, type RelayResponse, type Snapshot, type VoiceState } from "./types.js";
2
+ import { type IdentityAuthentication } from "./auth.js";
3
+ import { createApi } from "./http.js";
4
+ import { Channel, ChannelMessage, type ChannelOptions } from "./channel.js";
5
+ import type { DirectCursor, DirectPacket, DirectPage, DirectPeer } from "./direct-crypto.js";
6
+ import { type Transport } from "./transport.js";
7
+ export interface SessionMedia {
8
+ readonly channelId: string;
9
+ readonly voice: VoiceState["voice"];
10
+ readonly error: string | null;
11
+ update(snapshot: Snapshot): void;
12
+ event(type: string, payload: unknown): void;
13
+ setVolume(accountId: string, level: number): void;
14
+ close(): void;
15
+ }
16
+ export interface SessionMediaAdapter {
17
+ resume(): void;
18
+ open(channelId: string, connectionId: string, request: <T>(type: string, payload: unknown) => Promise<T>, onChange: () => void, volumes: Record<string, number>): SessionMedia;
19
+ stop(): void;
20
+ }
21
+ export interface SessionOptions {
22
+ transport?: Transport;
23
+ media?: SessionMediaAdapter;
24
+ }
25
+ export interface ClientEvents {
26
+ state: VoiceState;
27
+ ready: Snapshot;
28
+ messageCreate: ChannelMessage;
29
+ messageUpdate: {
30
+ id: string;
31
+ text: string;
32
+ html?: string;
33
+ editedAt: number;
34
+ };
35
+ messageDelete: {
36
+ id: string;
37
+ };
38
+ directMessage: DirectMessage;
39
+ directMessageChange: DirectMessageChange;
40
+ poke: Poke;
41
+ raw: {
42
+ type: string;
43
+ payload: unknown;
44
+ };
45
+ }
46
+ export type ConnectOptions = Omit<IdentityAuthentication, "serverId" | "action"> & Partial<Pick<IdentityAuthentication, "serverId" | "action">>;
47
+ /** A signed-in connection to one server. */
48
+ export declare class KoreroClient {
49
+ readonly origin: string;
50
+ readonly api: ReturnType<typeof createApi>;
51
+ private readonly transport;
52
+ private readonly media?;
53
+ private readonly listeners;
54
+ private currentState;
55
+ private credentials?;
56
+ private authenticating;
57
+ private starting?;
58
+ private refresh?;
59
+ private socket?;
60
+ private heartbeat?;
61
+ private nextId;
62
+ private voice?;
63
+ private volumes;
64
+ private pending;
65
+ private snapshot;
66
+ private messages;
67
+ private directMessages;
68
+ private lastPoke?;
69
+ /** A channel whose chat is followed without joining it. */
70
+ private viewedChannelId;
71
+ private viewRequest?;
72
+ /** Maps history requests to deletions received during the request, or null once settled. */
73
+ private loadedHistory;
74
+ private closed;
75
+ constructor(origin: string, options?: SessionOptions);
76
+ get state(): VoiceState;
77
+ on<K extends keyof ClientEvents>(event: K, listener: (value: ClientEvents[K]) => void): this;
78
+ off<K extends keyof ClientEvents>(event: K, listener: (value: ClientEvents[K]) => void): this;
79
+ once<K extends keyof ClientEvents>(event: K, listener: (value: ClientEvents[K]) => void): this;
80
+ private emit;
81
+ private update;
82
+ channel(id: string): Channel;
83
+ /** Signs in and opens signaling. Pass a known server ID to pin the identity challenge to it. */
84
+ connect({ serverId, action, ...options }: ConnectOptions): Promise<Snapshot>;
85
+ get connectionId(): string | undefined;
86
+ get channelId(): string | null;
87
+ resumeAudio(): void;
88
+ authenticate(options: IdentityAuthentication): Promise<RelayResponse>;
89
+ private identityRequest;
90
+ private post;
91
+ private accessToken;
92
+ fetch(request: Request): Promise<Response>;
93
+ private ticket;
94
+ start(volumes?: Record<string, number>): Promise<void>;
95
+ private open;
96
+ /** Fetches direct messages queued while offline, then acknowledges them. */
97
+ private receiveQueued;
98
+ private addDirectMessage;
99
+ rpc<T = unknown>(type: string, payload?: unknown): Promise<T>;
100
+ private showSnapshot;
101
+ /** The joined channel and the viewed channel, whose messages this session keeps. */
102
+ private chatChannels;
103
+ private syncChat;
104
+ private loadHistory;
105
+ viewChannel(connectionId: string, channelId: string | null): Promise<void>;
106
+ private updateVoice;
107
+ private show;
108
+ private event;
109
+ joinChannel(channelId: string, password?: string): Promise<void>;
110
+ leaveChannel(): Promise<void>;
111
+ setPresence(payload: Record<string, unknown> | undefined): Promise<void>;
112
+ setMemberVolume(accountId: string, level: number): void;
113
+ sendMessage(channelId: string, text: string, html?: string): Promise<{
114
+ messageId: string;
115
+ }>;
116
+ editMessage(messageId: string, text: string, html?: string): Promise<void>;
117
+ deleteMessage(messageId: string): Promise<void>;
118
+ screenRequest<T>(connectionId: string, channelId: string, kind: string, payload: unknown): Promise<T>;
119
+ directRequest<T>(connectionId: string, kind: DirectOperation, payload: unknown): Promise<T>;
120
+ createChannel(options: ChannelOptions & {
121
+ name: string;
122
+ temporary?: boolean;
123
+ }): Promise<Channel>;
124
+ directPeer(accountId: string): Promise<DirectPeer & {
125
+ ownPublicKey: string;
126
+ }>;
127
+ directHistory(accountId: string, before?: DirectCursor): Promise<DirectPage>;
128
+ sendDirect(packet: DirectPacket): Promise<{
129
+ messageId: string;
130
+ queued: boolean;
131
+ }>;
132
+ editDirect(packet: DirectPacket): Promise<unknown>;
133
+ deleteDirect(accountId: string, id: string): Promise<unknown>;
134
+ poke(accountId: string, message?: string): Promise<unknown>;
135
+ saveChannel(payload: ChannelOptions & {
136
+ channelId?: string;
137
+ temporary?: boolean;
138
+ }): Promise<string>;
139
+ deleteChannel(channelId: string): Promise<void>;
140
+ memberAction({ kind, payload }: MemberRequest): Promise<void>;
141
+ private closeSocket;
142
+ disconnect(): Promise<void>;
143
+ }