y-openrtc 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.
package/LICENSE ADDED
@@ -0,0 +1,92 @@
1
+ Required Notice: Copyright (c) 2026 Bryant Hargreaves and OpenRTC contributors.
2
+ Licensor Line of Business: OpenRTC realtime collaboration runtime, SDKs, developer services, and related tools (https://openrtc.app)
3
+
4
+ # PolyForm Shield License 1.0.0
5
+
6
+ <https://polyformproject.org/licenses/shield/1.0.0>
7
+
8
+ ## Acceptance
9
+
10
+ In order to get any license under these terms, you must agree to them as both strict obligations and conditions to all your licenses.
11
+
12
+ ## Copyright License
13
+
14
+ The licensor grants you a copyright license for the software to do everything you might do with the software that would otherwise infringe the licensor's copyright in it for any permitted purpose. However, you may only distribute the software according to [Distribution License](#distribution-license) and make changes or new works based on the software according to [Changes and New Works License](#changes-and-new-works-license).
15
+
16
+ ## Distribution License
17
+
18
+ The licensor grants you an additional copyright license to distribute copies of the software. Your license to distribute covers distributing the software with changes and new works permitted by [Changes and New Works License](#changes-and-new-works-license).
19
+
20
+ ## Notices
21
+
22
+ You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms or the URL for them above, as well as copies of any plain-text lines beginning with `Required Notice:` that the licensor provided with the software. For example:
23
+
24
+ > Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
25
+
26
+ ## Changes and New Works License
27
+
28
+ The licensor grants you an additional copyright license to make changes and new works based on the software for any permitted purpose.
29
+
30
+ ## Patent License
31
+
32
+ The licensor grants you a patent license for the software that covers patent claims the licensor can license, or becomes able to license, that you would infringe by using the software.
33
+
34
+ ## Noncompete
35
+
36
+ Any purpose is a permitted purpose, except for providing any product that competes with the software or any product the licensor or any of its affiliates provides using the software.
37
+
38
+ ## Competition
39
+
40
+ Goods and services compete even when they provide functionality through different kinds of interfaces or for different technical platforms. Applications can compete with services, libraries with plugins, frameworks with development tools, and so on, even if they're written in different programming languages or for different computer architectures. Goods and services compete even when provided free of charge. If you market a product as a practical substitute for the software or another product, it definitely competes.
41
+
42
+ ## New Products
43
+
44
+ If you are using the software to provide a product that does not compete, but the licensor or any of its affiliates brings your product into competition by providing a new version of the software or another product using the software, you may continue using versions of the software available under these terms beforehand to provide your competing product, but not any later versions.
45
+
46
+ ## Discontinued Products
47
+
48
+ You may begin using the software to compete with a product or service that the licensor or any of its affiliates has stopped providing, unless the licensor includes a plain-text line beginning with `Licensor Line of Business:` with the software that mentions that line of business. For example:
49
+
50
+ > Licensor Line of Business: YoyodyneCMS Content Management System (http://example.com/cms)
51
+
52
+ ## Sales of Business
53
+
54
+ If the licensor or any of its affiliates sells a line of business developing the software or using the software to provide a product, the buyer can also enforce [Noncompete](#noncompete) for that product.
55
+
56
+ ## Fair Use
57
+
58
+ You may have "fair use" rights for the software under the law. These terms do not limit them.
59
+
60
+ ## No Other Rights
61
+
62
+ These terms do not allow you to sublicense or transfer any of your licenses to anyone else, or prevent the licensor from granting licenses to anyone else. These terms do not imply any other licenses.
63
+
64
+ ## Patent Defense
65
+
66
+ If you make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company.
67
+
68
+ ## Violations
69
+
70
+ The first time you are notified in writing that you have violated any of these terms, or done anything with the software not covered by your licenses, your licenses can nonetheless continue if you come into full compliance with these terms, and take practical steps to correct past violations, within 32 days of receiving notice. Otherwise, all your licenses end immediately.
71
+
72
+ ## No Liability
73
+
74
+ ***As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.***
75
+
76
+ ## Definitions
77
+
78
+ The **licensor** is the individual or entity offering these terms, and the **software** is the software the licensor makes available under these terms.
79
+
80
+ A **product** can be a good or service, or a combination of them.
81
+
82
+ **You** refers to the individual or entity agreeing to these terms.
83
+
84
+ **Your company** is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all its affiliates.
85
+
86
+ **Affiliates** means the other organizations than an organization has control over, is under the control of, or is under common control with.
87
+
88
+ **Control** means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect.
89
+
90
+ **Your licenses** are all the licenses granted to you for the software under these terms.
91
+
92
+ **Use** means anything you do with the software requiring one of your licenses.
package/README.md ADDED
@@ -0,0 +1,92 @@
1
+ # y-openrtc
2
+
3
+ `y-openrtc` is a Yjs provider that feels close to `y-webrtc`, but uses OpenRTC for room membership and peer transport.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pnpm add y-openrtc yjs
9
+ ```
10
+
11
+ ## Minimal usage
12
+
13
+ ```ts
14
+ import * as Y from 'yjs';
15
+ import { OpenrtcProvider } from 'y-openrtc';
16
+
17
+ const doc = new Y.Doc();
18
+ const provider = new OpenrtcProvider('my-room', doc, {
19
+ apiKey: '<your public OpenRTC API key>',
20
+ });
21
+ ```
22
+
23
+ ## Advanced usage
24
+
25
+ ```ts
26
+ import * as Y from 'yjs';
27
+ import { OpenRTC } from 'openrtc';
28
+ import { OpenrtcProvider } from 'y-openrtc';
29
+
30
+ const client = OpenRTC({
31
+ apiKey: '<your public OpenRTC API key>',
32
+ });
33
+
34
+ const doc = new Y.Doc();
35
+ const provider = new OpenrtcProvider('my-room', doc, {
36
+ runtime: client,
37
+ });
38
+ ```
39
+
40
+ ## Transport and strict-mode options
41
+
42
+ `OpenrtcProvider` forwards OpenRTC transport options when it creates its own runtime:
43
+
44
+ ```ts
45
+ const provider = new OpenrtcProvider('private-room', doc, {
46
+ apiKey: '<your public OpenRTC API key>',
47
+ strictMode: true,
48
+ transports: {
49
+ iroh: true,
50
+ webrtc: {
51
+ privacyMode: true,
52
+ useTurn: true,
53
+ },
54
+ moq: true,
55
+ },
56
+ turnCredentialsProvider: async () => ({
57
+ iceServers: [{
58
+ urls: ['turn:turn.example.com:3478?transport=udp'],
59
+ username: 'short-lived-user',
60
+ credential: 'short-lived-credential',
61
+ }],
62
+ }),
63
+ });
64
+ ```
65
+
66
+ Keep TURN credentials server-generated and short lived. Do not commit `.env` files or long-lived secrets.
67
+
68
+ ## Differences from `y-webrtc`
69
+
70
+ - `signaling` and `peerOpts` are accepted for compatibility, but ignored.
71
+ - OpenRTC remains the source of truth for room membership and peer transport.
72
+ - Same-tab sync still prefers `BroadcastChannel` when available.
73
+ - `password` encrypts provider payloads end-to-end on top of OpenRTC.
74
+
75
+ ## Live test env
76
+
77
+ The live test at `tests/OpenrtcProvider.live.test.ts` reads package-local env values.
78
+
79
+ Create `openrtc/packages/y-openrtc/.env.local` with:
80
+
81
+ ```bash
82
+ OPENRTC_LIVE_TESTS=1
83
+ OPENRTC_Y_OPENRTC_API_KEY=<your public OpenRTC API key>
84
+ ```
85
+
86
+ Then run:
87
+
88
+ ```bash
89
+ pnpm --dir openrtc/packages/y-openrtc test:live
90
+ ```
91
+
92
+ The live test only uses the public OpenRTC API key. Server secrets are not needed for this package-local live test and should stay server-side.
@@ -0,0 +1,25 @@
1
+ export interface BroadcastMeshTransportOptions {
2
+ channelName: string;
3
+ providerId: string;
4
+ nodeId: string | null;
5
+ onPeerMessage: (message: {
6
+ action: 'add' | 'remove';
7
+ providerId: string;
8
+ nodeId: string | null;
9
+ }) => void;
10
+ onPayload: (message: {
11
+ providerId: string;
12
+ nodeId: string | null;
13
+ data: Uint8Array;
14
+ }) => void;
15
+ }
16
+ export declare class BroadcastMeshTransport {
17
+ private readonly options;
18
+ private channel;
19
+ constructor(options: BroadcastMeshTransportOptions);
20
+ get available(): boolean;
21
+ connect(): boolean;
22
+ announcePresence(): void;
23
+ sendPayload(data: Uint8Array): void;
24
+ disconnect(): void;
25
+ }
@@ -0,0 +1,65 @@
1
+ export class BroadcastMeshTransport {
2
+ constructor(options) {
3
+ this.channel = null;
4
+ this.options = options;
5
+ }
6
+ get available() {
7
+ return typeof globalThis.BroadcastChannel === 'function';
8
+ }
9
+ connect() {
10
+ if (!this.available || this.channel) {
11
+ return !!this.channel;
12
+ }
13
+ this.channel = new BroadcastChannel(this.options.channelName);
14
+ this.channel.onmessage = (event) => {
15
+ const message = event.data;
16
+ if (!message || message.providerId === this.options.providerId) {
17
+ return;
18
+ }
19
+ if (message.kind === 'peer') {
20
+ this.options.onPeerMessage({
21
+ action: message.action,
22
+ providerId: message.providerId,
23
+ nodeId: message.nodeId,
24
+ });
25
+ return;
26
+ }
27
+ this.options.onPayload({
28
+ providerId: message.providerId,
29
+ nodeId: message.nodeId,
30
+ data: message.data,
31
+ });
32
+ };
33
+ this.announcePresence();
34
+ return true;
35
+ }
36
+ announcePresence() {
37
+ this.channel?.postMessage({
38
+ kind: 'peer',
39
+ action: 'add',
40
+ providerId: this.options.providerId,
41
+ nodeId: this.options.nodeId,
42
+ });
43
+ }
44
+ sendPayload(data) {
45
+ this.channel?.postMessage({
46
+ kind: 'payload',
47
+ providerId: this.options.providerId,
48
+ nodeId: this.options.nodeId,
49
+ data,
50
+ });
51
+ }
52
+ disconnect() {
53
+ if (!this.channel) {
54
+ return;
55
+ }
56
+ this.channel.postMessage({
57
+ kind: 'peer',
58
+ action: 'remove',
59
+ providerId: this.options.providerId,
60
+ nodeId: this.options.nodeId,
61
+ });
62
+ this.channel.close();
63
+ this.channel = null;
64
+ }
65
+ }
@@ -0,0 +1,18 @@
1
+ import * as awarenessProtocol from 'y-protocols/awareness';
2
+ import type * as Y from 'yjs';
3
+ export declare const MESSAGE_SYNC = 0;
4
+ export declare const MESSAGE_AWARENESS = 1;
5
+ export declare const MESSAGE_QUERY_AWARENESS = 3;
6
+ export interface ApplyProviderMessageOptions {
7
+ doc: Y.Doc;
8
+ awareness: awarenessProtocol.Awareness;
9
+ payload: Uint8Array;
10
+ origin: unknown;
11
+ onSynced?: () => void;
12
+ }
13
+ export declare function encodeSyncStep1(doc: Y.Doc): Uint8Array;
14
+ export declare function encodeSyncStep2(doc: Y.Doc): Uint8Array;
15
+ export declare function encodeDocUpdate(update: Uint8Array): Uint8Array;
16
+ export declare function encodeAwarenessQuery(): Uint8Array;
17
+ export declare function encodeAwarenessUpdate(awareness: awarenessProtocol.Awareness, clients: number[]): Uint8Array;
18
+ export declare function applyProviderMessage(options: ApplyProviderMessageOptions): Uint8Array[];
package/dist/codec.js ADDED
@@ -0,0 +1,65 @@
1
+ import * as decoding from 'lib0/decoding';
2
+ import * as encoding from 'lib0/encoding';
3
+ import * as awarenessProtocol from 'y-protocols/awareness';
4
+ import * as syncProtocol from 'y-protocols/sync';
5
+ export const MESSAGE_SYNC = 0;
6
+ export const MESSAGE_AWARENESS = 1;
7
+ export const MESSAGE_QUERY_AWARENESS = 3;
8
+ export function encodeSyncStep1(doc) {
9
+ const encoder = encoding.createEncoder();
10
+ encoding.writeVarUint(encoder, MESSAGE_SYNC);
11
+ syncProtocol.writeSyncStep1(encoder, doc);
12
+ return encoding.toUint8Array(encoder);
13
+ }
14
+ export function encodeSyncStep2(doc) {
15
+ const encoder = encoding.createEncoder();
16
+ encoding.writeVarUint(encoder, MESSAGE_SYNC);
17
+ syncProtocol.writeSyncStep2(encoder, doc);
18
+ return encoding.toUint8Array(encoder);
19
+ }
20
+ export function encodeDocUpdate(update) {
21
+ const encoder = encoding.createEncoder();
22
+ encoding.writeVarUint(encoder, MESSAGE_SYNC);
23
+ syncProtocol.writeUpdate(encoder, update);
24
+ return encoding.toUint8Array(encoder);
25
+ }
26
+ export function encodeAwarenessQuery() {
27
+ const encoder = encoding.createEncoder();
28
+ encoding.writeVarUint(encoder, MESSAGE_QUERY_AWARENESS);
29
+ return encoding.toUint8Array(encoder);
30
+ }
31
+ export function encodeAwarenessUpdate(awareness, clients) {
32
+ const encoder = encoding.createEncoder();
33
+ encoding.writeVarUint(encoder, MESSAGE_AWARENESS);
34
+ encoding.writeVarUint8Array(encoder, awarenessProtocol.encodeAwarenessUpdate(awareness, clients));
35
+ return encoding.toUint8Array(encoder);
36
+ }
37
+ export function applyProviderMessage(options) {
38
+ const decoder = decoding.createDecoder(options.payload);
39
+ const messageType = decoding.readVarUint(decoder);
40
+ switch (messageType) {
41
+ case MESSAGE_SYNC: {
42
+ const encoder = encoding.createEncoder();
43
+ encoding.writeVarUint(encoder, MESSAGE_SYNC);
44
+ const syncMessageType = syncProtocol.readSyncMessage(decoder, encoder, options.doc, options.origin);
45
+ if (syncMessageType === syncProtocol.messageYjsSyncStep2) {
46
+ options.onSynced?.();
47
+ }
48
+ if (syncMessageType === syncProtocol.messageYjsSyncStep1) {
49
+ return [encoding.toUint8Array(encoder)];
50
+ }
51
+ return [];
52
+ }
53
+ case MESSAGE_QUERY_AWARENESS: {
54
+ return [
55
+ encodeAwarenessUpdate(options.awareness, Array.from(options.awareness.getStates().keys())),
56
+ ];
57
+ }
58
+ case MESSAGE_AWARENESS: {
59
+ awarenessProtocol.applyAwarenessUpdate(options.awareness, decoding.readVarUint8Array(decoder), options.origin);
60
+ return [];
61
+ }
62
+ default:
63
+ return [];
64
+ }
65
+ }
@@ -0,0 +1,3 @@
1
+ export declare function deriveRoomKey(password: string | null | undefined, roomName: string): Promise<CryptoKey | null>;
2
+ export declare function encryptFrame(payload: Uint8Array, key: CryptoKey | null): Promise<Uint8Array>;
3
+ export declare function decryptFrame(payload: Uint8Array, key: CryptoKey | null): Promise<Uint8Array>;
package/dist/crypto.js ADDED
@@ -0,0 +1,56 @@
1
+ const encoder = new TextEncoder();
2
+ const PASSWORD_KDF_ITERATIONS = 210000;
3
+ function concatBytes(...arrays) {
4
+ const total = arrays.reduce((sum, array) => sum + array.byteLength, 0);
5
+ const merged = new Uint8Array(total);
6
+ let offset = 0;
7
+ for (const array of arrays) {
8
+ merged.set(array, offset);
9
+ offset += array.byteLength;
10
+ }
11
+ return merged;
12
+ }
13
+ export async function deriveRoomKey(password, roomName) {
14
+ if (!password) {
15
+ return null;
16
+ }
17
+ const subtle = globalThis.crypto?.subtle;
18
+ if (!subtle) {
19
+ throw new Error('Password support requires Web Crypto (crypto.subtle).');
20
+ }
21
+ const baseKey = await subtle.importKey('raw', encoder.encode(password), 'PBKDF2', false, ['deriveKey']);
22
+ return subtle.deriveKey({
23
+ name: 'PBKDF2',
24
+ salt: encoder.encode(`openrtc-yjs-room:${roomName}`),
25
+ iterations: PASSWORD_KDF_ITERATIONS,
26
+ hash: 'SHA-256',
27
+ }, baseKey, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
28
+ }
29
+ export async function encryptFrame(payload, key) {
30
+ if (!key) {
31
+ return payload;
32
+ }
33
+ const subtle = globalThis.crypto?.subtle;
34
+ if (!subtle) {
35
+ throw new Error('Password support requires Web Crypto (crypto.subtle).');
36
+ }
37
+ const iv = globalThis.crypto.getRandomValues(new Uint8Array(12));
38
+ const cipherBuffer = await subtle.encrypt({ name: 'AES-GCM', iv }, key, payload);
39
+ return concatBytes(new Uint8Array([1]), iv, new Uint8Array(cipherBuffer));
40
+ }
41
+ export async function decryptFrame(payload, key) {
42
+ if (!key) {
43
+ return payload;
44
+ }
45
+ if (payload.byteLength < 14 || payload[0] !== 1) {
46
+ throw new Error('Encrypted provider payload is malformed.');
47
+ }
48
+ const subtle = globalThis.crypto?.subtle;
49
+ if (!subtle) {
50
+ throw new Error('Password support requires Web Crypto (crypto.subtle).');
51
+ }
52
+ const iv = payload.slice(1, 13);
53
+ const cipher = payload.slice(13);
54
+ const plainBuffer = await subtle.decrypt({ name: 'AES-GCM', iv }, key, cipher);
55
+ return new Uint8Array(plainBuffer);
56
+ }
@@ -0,0 +1,3 @@
1
+ export { OpenrtcProvider, } from './provider.js';
2
+ export { roomNameToOpenrtcRoomId } from './roomName.js';
3
+ export type { OpenrtcAuthMode, OpenrtcProviderEvents, OpenrtcProviderOptions, OpenrtcTransports, PeersEventPayload, StatusEventPayload, SyncedEventPayload, } from './types.js';
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { OpenrtcProvider, } from './provider.js';
2
+ export { roomNameToOpenrtcRoomId } from './roomName.js';
@@ -0,0 +1,82 @@
1
+ import * as awarenessProtocol from 'y-protocols/awareness';
2
+ import type * as Y from 'yjs';
3
+ import type { OpenrtcProviderEvents, OpenrtcProviderOptions } from './types.js';
4
+ type EventName = keyof OpenrtcProviderEvents;
5
+ type EventListener<K extends EventName> = (payload: OpenrtcProviderEvents[K]) => void;
6
+ export declare class OpenrtcProvider {
7
+ readonly roomName: string;
8
+ readonly doc: Y.Doc;
9
+ readonly awareness: awarenessProtocol.Awareness;
10
+ readonly maxConns: number;
11
+ private readonly options;
12
+ private readonly providerId;
13
+ private readonly listeners;
14
+ private readonly keyPromise;
15
+ private readonly filterBcConns;
16
+ private readonly docUpdateHandler;
17
+ private readonly awarenessUpdateHandler;
18
+ private readonly destroyHandler;
19
+ private runtimeLease;
20
+ private runtime;
21
+ private roomId;
22
+ private localNodeId;
23
+ private broadcastTransport;
24
+ private stopWatchingRoom;
25
+ private stopRuntimeConnections;
26
+ private stopRuntimeConnectionStates;
27
+ private readonly roomMembers;
28
+ private readonly openrtcConnections;
29
+ private readonly bcPeers;
30
+ private readonly pendingNodeIds;
31
+ private shouldConnect;
32
+ private destroyed;
33
+ private synced;
34
+ private localObserversAttached;
35
+ private connectPromise;
36
+ private reconcileTimer;
37
+ private runtimeRefreshTimer;
38
+ private readonly diagnostics;
39
+ constructor(roomName: string, doc: Y.Doc, options?: OpenrtcProviderOptions);
40
+ get connected(): boolean;
41
+ on<K extends EventName>(name: K, listener: EventListener<K>): EventListener<K>;
42
+ off<K extends EventName>(name: K, listener: EventListener<K>): void;
43
+ once<K extends EventName>(name: K, listener: EventListener<K>): void;
44
+ emit<K extends EventName>(name: K, payload: OpenrtcProviderEvents[K]): void;
45
+ connect(): void;
46
+ disconnect(): void;
47
+ destroy(): void;
48
+ diagnosticSnapshot(): typeof this.diagnostics;
49
+ private warnCompatibilityOptions;
50
+ private emitStatus;
51
+ private emitSynced;
52
+ private emitPeers;
53
+ private attachLocalObservers;
54
+ private detachLocalObservers;
55
+ private connectInternal;
56
+ private connectWithRetry;
57
+ private resolveRoomCandidates;
58
+ private joinFirstAvailableRoom;
59
+ private joinOrCreateRuntimeRoom;
60
+ private joinRoomAfterCreate;
61
+ private requestReconcile;
62
+ private replaceRoomMembers;
63
+ private reconcilePeers;
64
+ private hasBcNodeId;
65
+ private isRelevantConnection;
66
+ private refreshKnownRuntimeConnections;
67
+ private startRuntimeConnectionRefresh;
68
+ private resyncPeer;
69
+ private sendInitialSync;
70
+ private attachConnection;
71
+ private sendToConnection;
72
+ private sendControlToConnection;
73
+ private sendBroadcastPayload;
74
+ private broadcastProviderPayload;
75
+ private broadcastInitialBcState;
76
+ private handleIncomingPayload;
77
+ private updateSyncedState;
78
+ private disconnectOwnedResources;
79
+ private disconnectInternal;
80
+ private destroyInternal;
81
+ }
82
+ export {};