@lynkoria/server 0.2.0 → 0.3.1

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/CHANGELOG.md CHANGED
@@ -1,5 +1,28 @@
1
1
  # @lynkoria/server
2
2
 
3
+ ## 0.3.1
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies
8
+ - @lynkoria/contracts@0.4.0
9
+
10
+ ## 0.3.0
11
+
12
+ ### Minor Changes
13
+
14
+ - General-purpose messaging primitives. Conversations gain `description`, product `metadata`, `visibility` (`private` | `public`) and a read-only archive state; members gain `owner` | `admin` | `member` | `viewer` roles (viewers are read-only) and a per-user `notificationLevel`. Messages carry `mentions` (validated against current members), pins with sequenced `message.pinned`/`message.unpinned` events, one-level `thread` summaries, and events report their `actorId`. Conversation views include member counts, dm members and the caller's role, `unreadCount` and `mentionCount`.
15
+
16
+ - `@lynkoria/client`: `conversations.get`, `conversations.members`, `conversations.list({ scope: 'public', query })`, `conversations.setNotificationLevel`, `messages.get`, `messages.pin`/`unpin`/`pins`, `messages.search`, mentions on `send`/`edit`, and `history` filters (`threadId`, `topLevel`, `withAttachments`).
17
+ - `@lynkoria/server`: `conversations.get`/`update`/`members`/`member`/`setRole`, `addMembers(..., { role })`, `sessions.revoke`, `users.setPresence`, `users.removeFromTenant`, and an auto-batching, idempotent `import` API (`messages`, `readPositions`, `attachment`) for keys with the new `messaging:import` scope.
18
+ - `@lynkoria/react`: `useConversation(id, { threadId | topLevel })` keeps thread summaries current and shares ordering state between views; `send` accepts mentions; new `useConversationList` hook with live unread and mention badges.
19
+ - Messaging tokens accept `scopes` (`presence`, `public_conversations`) so products can mint restricted guest tokens.
20
+
21
+ ### Patch Changes
22
+
23
+ - Updated dependencies
24
+ - @lynkoria/contracts@0.3.0
25
+
3
26
  ## 0.2.0
4
27
 
5
28
  ### Minor Changes
package/README.md CHANGED
@@ -10,7 +10,11 @@ presence. It also creates calls and conversations, moderates users and verifies
10
10
  > Keep the service key on the server. Never ship it to a browser or mobile app.
11
11
 
12
12
  **[Documentation](https://lynkoria.com/docs/)** · [Server SDK guide](https://lynkoria.com/docs/server-sdk/) ·
13
- [Quickstart](https://lynkoria.com/docs/quickstart/) · [Webhooks](https://lynkoria.com/docs/webhooks/)
13
+ [Getting started](https://lynkoria.com/docs/getting-started/) · [Webhooks](https://lynkoria.com/docs/webhooks/)
14
+
15
+ **Before you start:** you need a Lynkoria project and a service key from the
16
+ [Lynkoria Console](https://console.lynkoria.com). [Getting started](https://lynkoria.com/docs/getting-started/)
17
+ walks through your account, project setup, keys and a first test.
14
18
 
15
19
  ## Install
16
20
 
@@ -65,14 +69,15 @@ Return the join credentials and `messagingToken` to your app, which passes them
65
69
 
66
70
  ## What it covers
67
71
 
68
- | Area | Methods | Guide |
69
- | ------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ |
70
- | Calls | `calls.create`, `get`, `joinToken`, `end`, `removeParticipant`, `removeUser`, `setRole`, `signal` | [Calls](https://lynkoria.com/docs/calls/) |
71
- | Messaging | `sessions.messagingToken`, `conversations.create`, `addMembers`, `removeMember` | [Messaging](https://lynkoria.com/docs/messaging/) |
72
- | Users | `users.suspend`, `unsuspend` | [Server SDK](https://lynkoria.com/docs/server-sdk/) |
73
- | Notifications | `notifications.send` | [Push](https://lynkoria.com/docs/push-notifications/) |
74
- | Recordings | `recordings.start`, `list`, `get`, `stop`, `download`, `delete` | [Recording](https://lynkoria.com/docs/recording-and-egress/) |
75
- | Webhooks | `webhooks.verify`, or the standalone `verifyWebhook` | [Webhooks](https://lynkoria.com/docs/webhooks/) |
72
+ | Area | Methods | Guide |
73
+ | ------------- | ------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- |
74
+ | Calls | `calls.create`, `get`, `joinToken`, `end`, `removeParticipant`, `removeUser`, `setRole`, `signal` | [Calls](https://lynkoria.com/docs/calls/) |
75
+ | Messaging | `sessions.messagingToken` (scopes), `conversations.create`, `get`, `update`, `members`, `addMembers`, `setRole`, `removeMember` | [Messaging](https://lynkoria.com/docs/messaging/) |
76
+ | Users | `users.suspend`, `unsuspend`, `setPresence`, `removeFromTenant`, `sessions.revoke` | [Server SDK](https://lynkoria.com/docs/server-sdk/) |
77
+ | Import | `import.messages`, `readPositions`, `attachment` (scope `messaging:import`) | [Importing history](https://lynkoria.com/docs/importing-history/) |
78
+ | Notifications | `notifications.send` | [Push](https://lynkoria.com/docs/push-notifications/) |
79
+ | Recordings | `recordings.start`, `list`, `get`, `stop`, `download`, `delete` | [Recording](https://lynkoria.com/docs/recording-and-egress/) |
80
+ | Webhooks | `webhooks.verify`, or the standalone `verifyWebhook` | [Webhooks](https://lynkoria.com/docs/webhooks/) |
76
81
 
77
82
  The full method list is in the [server SDK reference](https://lynkoria.com/docs/server-sdk/).
78
83
 
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Call, CallSignalRequest, Conversation, CreateCallRequest, CreateConversationRequest, ErrorCode, JoinTokenRequest, JoinTokenResponse, LynkoriaError, MessagingTokenRequest, MessagingTokenResponse, ParticipantRole, Recording, RecordingDownload, RemoveUserResponse, SendNotificationRequest, SendNotificationResponse, StartRecordingRequest, WEBHOOK_SIGNATURE_HEADER, WebhookEvent } from "@lynkoria/contracts";
1
+ import { Attachment, Call, CallSignalRequest, Conversation, ConversationMember, ConversationMemberPage, CreateCallRequest, CreateConversationRequest, ErrorCode, ImportMessage, ImportMessagesResponse, JoinTokenRequest, JoinTokenResponse, LynkoriaError, ManualStatus, MemberRole, MessagingTokenRequest, MessagingTokenResponse, NotificationLevel, ParticipantRole, Recording, RecordingDownload, RemoveUserResponse, SendNotificationRequest, SendNotificationResponse, StartRecordingRequest, UpdateConversationRequest, WEBHOOK_SIGNATURE_HEADER, WebhookEvent } from "@lynkoria/contracts";
2
2
  export type * from "@lynkoria/contracts";
3
3
  /** The Lynkoria API. */
4
4
  export declare const DEFAULT_API_URL = "https://api.lynkoria.com";
@@ -37,16 +37,77 @@ export type LynkoriaServer = {
37
37
  };
38
38
  sessions: {
39
39
  messagingToken(input: MessagingTokenRequest): Promise<MessagingTokenResponse>;
40
+ /**
41
+ * Ends the user's realtime sessions and rejects messaging tokens issued until now, for every
42
+ * session or only one tenant and/or device. Call it on sign-out or session revocation.
43
+ */
44
+ revoke(userId: string, scope?: {
45
+ tenantId?: string;
46
+ deviceId?: string;
47
+ }): Promise<void>;
40
48
  };
41
49
  users: {
42
50
  suspend(userId: string): Promise<void>;
43
51
  unsuspend(userId: string): Promise<void>;
52
+ /** Sets the user's manual presence status in a tenant (e.g. apply a do-not-disturb setting). */
53
+ setPresence(userId: string, input: {
54
+ tenantId?: string;
55
+ status: ManualStatus;
56
+ }): Promise<void>;
57
+ /**
58
+ * Removes the user from every conversation of the tenant and ends their sessions there; use it
59
+ * when someone leaves the workspace, organization or group the tenant represents.
60
+ */
61
+ removeFromTenant(tenantId: string, userId: string): Promise<{
62
+ conversations: number;
63
+ }>;
44
64
  };
45
65
  conversations: {
46
66
  create(input: CreateConversationRequest): Promise<Conversation>;
47
- addMembers(conversationId: string, userIds: string[]): Promise<void>;
67
+ get(conversationId: string): Promise<Conversation>;
68
+ update(conversationId: string, input: UpdateConversationRequest): Promise<Conversation>;
69
+ members(conversationId: string, params?: {
70
+ limit?: number;
71
+ cursor?: string;
72
+ }): Promise<ConversationMemberPage>;
73
+ addMembers(conversationId: string, userIds: string[], options?: {
74
+ role?: MemberRole;
75
+ }): Promise<void>;
76
+ /** One active member with their role; throws `not_found` when the user is not a member. */
77
+ member(conversationId: string, userId: string): Promise<ConversationMember>;
78
+ setRole(conversationId: string, userId: string, role: MemberRole): Promise<void>;
48
79
  removeMember(conversationId: string, userId: string): Promise<void>;
49
80
  };
81
+ /**
82
+ * History import from another messaging system. Needs a key with the `messaging:import` scope.
83
+ * Every call is idempotent: rerun after a failure and already imported items are skipped.
84
+ */
85
+ import: {
86
+ /** Imports messages oldest first, split into request-sized batches automatically. */
87
+ messages(conversationId: string, messages: ImportMessage[]): Promise<ImportMessagesResponse>;
88
+ /** Forward-only read positions, plus each member's notification level when given. */
89
+ readPositions(conversationId: string, positions: {
90
+ userId: string;
91
+ seq: number;
92
+ notificationLevel?: NotificationLevel;
93
+ }[]): Promise<{
94
+ updated: number;
95
+ missing: string[];
96
+ }>;
97
+ /**
98
+ * Uploads one file for a historical sender (presigned PUT, digest check, malware scan when
99
+ * configured) and returns the ready attachment to reference from `messages`.
100
+ */
101
+ attachment(input: {
102
+ conversationId: string;
103
+ uploaderId: string;
104
+ fileName: string;
105
+ mediaType: string;
106
+ data: Uint8Array | Blob;
107
+ /** Hex SHA-256 of `data`; computed when omitted. */
108
+ sha256?: string;
109
+ }): Promise<Attachment>;
110
+ };
50
111
  notifications: {
51
112
  /** Queues push notifications to users' registered devices; resolves with the queued count. */
52
113
  send(input: SendNotificationRequest): Promise<SendNotificationResponse>;
@@ -66,6 +127,8 @@ export type LynkoriaServer = {
66
127
  };
67
128
  };
68
129
  export declare function createLynkoriaServer(opts: LynkoriaServerOptions): LynkoriaServer;
130
+ /** Splits an import into ordered batches under the request limits. */
131
+ export declare function importBatches(messages: ImportMessage[]): ImportMessage[][];
69
132
  /** Standalone verifier: `t=<unix>,v1=<hex HMAC-SHA256(secret, "<t>.<rawBody>")>`; rejects stale timestamps. */
70
133
  export declare function verifyWebhook<T = Record<string, unknown>>(rawBody: string, header: string | null | undefined, secrets: string[], nowSeconds?: number): WebhookEvent<T>;
71
134
  export { ErrorCode, LynkoriaError, WEBHOOK_SIGNATURE_HEADER };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { createHmac, timingSafeEqual } from "node:crypto";
1
+ import { createHash, createHmac, timingSafeEqual } from "node:crypto";
2
2
  import { ErrorCode, ErrorCode as ErrorCode$1, LynkoriaError, LynkoriaError as LynkoriaError$1, WEBHOOK_SIGNATURE_HEADER, WEBHOOK_TOLERANCE_SECONDS } from "@lynkoria/contracts";
3
3
  // src/index.ts
4
4
  /** The Lynkoria API. */
@@ -70,16 +70,80 @@ function createLynkoriaServer(opts) {
70
70
  setRole: (callId, identity, role) => idempotent("POST", `/v1/calls/${enc(callId)}/participants/${enc(identity)}/permissions`, { role }),
71
71
  signal: (callId, input) => request("POST", `/v1/calls/${enc(callId)}/signal`, input)
72
72
  },
73
- sessions: { messagingToken: (input) => idempotent("POST", "/v1/sessions/messaging-token", input) },
73
+ sessions: {
74
+ messagingToken: (input) => idempotent("POST", "/v1/sessions/messaging-token", input),
75
+ revoke: (userId, scope = {}) => idempotent("POST", `/v1/users/${enc(userId)}/sessions/revoke`, scope)
76
+ },
74
77
  users: {
75
78
  suspend: (userId) => idempotent("POST", `/v1/users/${enc(userId)}/suspend`),
76
- unsuspend: (userId) => idempotent("DELETE", `/v1/users/${enc(userId)}/suspend`)
79
+ unsuspend: (userId) => idempotent("DELETE", `/v1/users/${enc(userId)}/suspend`),
80
+ setPresence: (userId, input) => idempotent("PUT", `/v1/users/${enc(userId)}/presence`, input),
81
+ removeFromTenant: (tenantId, userId) => idempotent("DELETE", `/v1/tenants/${enc(tenantId)}/members/${enc(userId)}`)
77
82
  },
78
83
  conversations: {
79
84
  create: (input) => request("POST", "/v1/conversations", input),
80
- addMembers: (id, userIds) => request("POST", `/v1/conversations/${enc(id)}/members`, { userIds }),
85
+ get: (id) => idempotent("GET", `/v1/conversations/${enc(id)}`),
86
+ update: (id, input) => idempotent("PATCH", `/v1/conversations/${enc(id)}`, input),
87
+ members: (id, params = {}) => {
88
+ const q = new URLSearchParams();
89
+ if (params.limit) q.set("limit", String(params.limit));
90
+ if (params.cursor) q.set("cursor", params.cursor);
91
+ return idempotent("GET", `/v1/conversations/${enc(id)}/members${q.size ? `?${q}` : ""}`);
92
+ },
93
+ addMembers: (id, userIds, options = {}) => request("POST", `/v1/conversations/${enc(id)}/members`, {
94
+ userIds,
95
+ ...options
96
+ }),
97
+ member: (id, userId) => idempotent("GET", `/v1/conversations/${enc(id)}/members/${enc(userId)}`),
98
+ setRole: (id, userId, role) => idempotent("PUT", `/v1/conversations/${enc(id)}/members/${enc(userId)}`, { role }),
81
99
  removeMember: (id, userId) => request("DELETE", `/v1/conversations/${enc(id)}/members/${enc(userId)}`)
82
100
  },
101
+ import: {
102
+ async messages(conversationId, messages) {
103
+ const total = {
104
+ imported: 0,
105
+ existing: 0,
106
+ items: [],
107
+ lastSeq: 0
108
+ };
109
+ for (const batch of importBatches(messages)) {
110
+ const res = await idempotent("POST", `/v1/import/conversations/${enc(conversationId)}/messages`, { messages: batch });
111
+ total.imported += res.imported;
112
+ total.existing += res.existing;
113
+ total.items.push(...res.items);
114
+ total.lastSeq = res.lastSeq;
115
+ }
116
+ return total;
117
+ },
118
+ async readPositions(conversationId, positions) {
119
+ const out = {
120
+ updated: 0,
121
+ missing: []
122
+ };
123
+ for (let i = 0; i < positions.length; i += 1e3) {
124
+ const res = await idempotent("PUT", `/v1/import/conversations/${enc(conversationId)}/read-positions`, { positions: positions.slice(i, i + 1e3) });
125
+ out.updated += res.updated;
126
+ out.missing.push(...res.missing);
127
+ }
128
+ return out;
129
+ },
130
+ async attachment({ data, sha256, ...input }) {
131
+ const bytes = data instanceof Uint8Array ? new Uint8Array(data) : new Uint8Array(await data.arrayBuffer());
132
+ const intent = await request("POST", "/v1/import/attachments/upload-intent", {
133
+ ...input,
134
+ size: bytes.byteLength,
135
+ sha256: sha256 ?? createHash("sha256").update(bytes).digest("hex")
136
+ });
137
+ const put = await doFetch(intent.uploadUrl, {
138
+ method: "PUT",
139
+ headers: intent.headers,
140
+ body: bytes,
141
+ signal: AbortSignal.timeout(Math.max(timeoutMs, 6e4))
142
+ });
143
+ if (!put.ok) throw new LynkoriaError$1(ErrorCode$1.BadRequest, `Attachment upload failed with HTTP ${put.status}`, put.status);
144
+ return idempotent("POST", `/v1/import/attachments/${enc(intent.attachment.id)}/complete`);
145
+ }
146
+ },
83
147
  notifications: { send: (input) => request("POST", "/v1/notifications", input) },
84
148
  recordings: {
85
149
  start: (callId, input) => request("POST", `/v1/calls/${enc(callId)}/recordings`, input),
@@ -92,6 +156,27 @@ function createLynkoriaServer(opts) {
92
156
  webhooks: { verify: (rawBody, header, nowSeconds) => verifyWebhook(rawBody, header, secrets, nowSeconds) }
93
157
  };
94
158
  }
159
+ /** The API accepts 200 messages and 256 KB per request; stay under both with JSON overhead. */
160
+ const IMPORT_BATCH_MESSAGES = 200;
161
+ const IMPORT_BATCH_BYTES = 204800;
162
+ /** Splits an import into ordered batches under the request limits. */
163
+ function importBatches(messages) {
164
+ const batches = [];
165
+ let current = [];
166
+ let bytes = 0;
167
+ for (const m of messages) {
168
+ const size = new TextEncoder().encode(JSON.stringify(m)).byteLength + 1;
169
+ if (current.length > 0 && (current.length >= IMPORT_BATCH_MESSAGES || bytes + size > IMPORT_BATCH_BYTES)) {
170
+ batches.push(current);
171
+ current = [];
172
+ bytes = 0;
173
+ }
174
+ current.push(m);
175
+ bytes += size;
176
+ }
177
+ if (current.length > 0) batches.push(current);
178
+ return batches;
179
+ }
95
180
  const retryAfterSeconds = /* @__PURE__ */ new WeakMap();
96
181
  const RETRYABLE_STATUS = /* @__PURE__ */ new Set([
97
182
  429,
@@ -125,4 +210,4 @@ function verifyWebhook(rawBody, header, secrets, nowSeconds = Math.floor(Date.no
125
210
  })) throw new LynkoriaError$1(ErrorCode$1.Unauthorized, "Invalid webhook signature");
126
211
  return JSON.parse(rawBody);
127
212
  }
128
- export { DEFAULT_API_URL, ErrorCode, LynkoriaError, WEBHOOK_SIGNATURE_HEADER, createLynkoriaServer, verifyWebhook };
213
+ export { DEFAULT_API_URL, ErrorCode, LynkoriaError, WEBHOOK_SIGNATURE_HEADER, createLynkoriaServer, importBatches, verifyWebhook };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lynkoria/server",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "description": "Lynkoria server SDK for product backends: calls, tokens, conversations, webhook verification",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -26,7 +26,7 @@
26
26
  "access": "public"
27
27
  },
28
28
  "dependencies": {
29
- "@lynkoria/contracts": "^0.2.0"
29
+ "@lynkoria/contracts": "^0.4.0"
30
30
  },
31
31
  "devDependencies": {
32
32
  "@lynkoria/config": "0.0.0",