@lynkoria/server 0.1.1 → 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 +52 -0
- package/README.md +37 -16
- package/dist/index.d.ts +74 -4
- package/dist/index.js +103 -8
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,57 @@
|
|
|
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
|
+
|
|
26
|
+
## 0.2.0
|
|
27
|
+
|
|
28
|
+
### Minor Changes
|
|
29
|
+
|
|
30
|
+
- e96fe9d: Call controls, added for products moving from Agora:
|
|
31
|
+
|
|
32
|
+
- `calls.create({ restartIfEnded: true })` starts a new call when the call for that `productCallId` has ended, so an ID can be reused like an Agora channel name (a meeting link people come back to). Without it, an ended ID still returns `409 conflict`.
|
|
33
|
+
- `calls.joinToken()` accepts `ttlSeconds` (30–300, default 300) and `publishSources` (for example `['camera', 'microphone']` to forbid screen sharing; enforced by the media server).
|
|
34
|
+
- `calls.removeUser(callId, userId)` disconnects every device of a user and resolves with how many were connected. An unused join token stays valid until it expires, so also stop issuing tokens to that user.
|
|
35
|
+
|
|
36
|
+
Requires the Lynkoria API released on or after 2026-11-18.
|
|
37
|
+
- 0ee4045: SDKs no longer need an API URL.
|
|
38
|
+
|
|
39
|
+
- `@lynkoria/server`: `baseUrl` is optional and defaults to `https://api.lynkoria.com` (exported as `DEFAULT_API_URL`); `createLynkoriaServer({ serviceKey })` is enough. It now throws in a browser or React Native app, where the service key would reach every user.
|
|
40
|
+
- `sessions.messagingToken()` returns `apiUrl` next to the token. Return the whole result from your token endpoint to the client: `@lynkoria/client` then needs no `baseUrl`, and only accepts an `https:` `apiUrl` (plain `http:` for localhost).
|
|
41
|
+
- `@lynkoria/client`: `getMessagingToken` is optional for calls-only apps; without it `connect()` does nothing and messaging methods reject with a clear error.
|
|
42
|
+
|
|
43
|
+
**Upgrade:** remove `baseUrl` from `createLynkoria` and `createLynkoriaServer` (existing values keep working), and return the full `messagingToken()` result instead of only `token`.
|
|
44
|
+
|
|
45
|
+
**Breaking for type users:** `MessagingTokenResponse` in `@lynkoria/contracts` has a required `apiUrl`. Code that constructs that type by hand (test mocks, fakes) must add it.
|
|
46
|
+
|
|
47
|
+
### Patch Changes
|
|
48
|
+
|
|
49
|
+
- 19ae236: Retries of idempotent operations now back off when a 429 or 5xx response has no `Retry-After` header; before, they retried immediately.
|
|
50
|
+
- 0a7c608: After you rotate a webhook signing secret in the console, Lynkoria signs each delivery with both the new and the previous secret for 24 hours. `webhooks.verify` accepts a delivery when any signature matches, so receivers can deploy the new secret without missing events. The README and docs show raw-body verification for Express, Hono, NestJS and Next.js.
|
|
51
|
+
- Updated dependencies [e96fe9d]
|
|
52
|
+
- Updated dependencies [0ee4045]
|
|
53
|
+
- @lynkoria/contracts@0.2.0
|
|
54
|
+
|
|
3
55
|
## 0.1.1
|
|
4
56
|
|
|
5
57
|
### Patch 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
|
-
[
|
|
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
|
|
|
@@ -26,13 +30,17 @@ Requires Node.js 22.12 or later. ES module with TypeScript types.
|
|
|
26
30
|
import { createLynkoriaServer } from '@lynkoria/server';
|
|
27
31
|
|
|
28
32
|
const lynkoria = createLynkoriaServer({
|
|
29
|
-
baseUrl: 'https://api.lynkoria.com',
|
|
30
33
|
serviceKey: process.env.LYNKORIA_SERVICE_KEY!,
|
|
31
34
|
webhookSecret: process.env.LYNKORIA_WEBHOOK_SECRET,
|
|
32
35
|
});
|
|
33
36
|
|
|
34
|
-
// 1. Create (or reuse) a call for something in your product.
|
|
35
|
-
|
|
37
|
+
// 1. Create (or reuse) a call for something in your product. restartIfEnded starts a new call
|
|
38
|
+
// when the previous one with this ID has ended (a meeting link people come back to).
|
|
39
|
+
const call = await lynkoria.calls.create({
|
|
40
|
+
productCallId: 'meeting_789',
|
|
41
|
+
type: 'group',
|
|
42
|
+
restartIfEnded: true,
|
|
43
|
+
});
|
|
36
44
|
|
|
37
45
|
// 2. After your own authorization checks, give this user a join token.
|
|
38
46
|
const { url, token } = await lynkoria.calls.joinToken({
|
|
@@ -41,38 +49,51 @@ const { url, token } = await lynkoria.calls.joinToken({
|
|
|
41
49
|
deviceId: session.deviceId,
|
|
42
50
|
displayName: session.displayName,
|
|
43
51
|
role: 'participant',
|
|
52
|
+
ttlSeconds: 120, // optional: time to connect, 30-300 (default 300)
|
|
53
|
+
publishSources: ['camera', 'microphone'], // optional: e.g. no screen sharing
|
|
44
54
|
});
|
|
45
55
|
|
|
46
56
|
// 3. Messaging: a short-lived token for @lynkoria/client.
|
|
47
|
-
|
|
57
|
+
// Return the whole result ({ token, expiresAt, apiUrl }) to the client unchanged.
|
|
58
|
+
const messagingToken = await lynkoria.sessions.messagingToken({
|
|
48
59
|
userId: session.userId,
|
|
49
60
|
deviceId: session.deviceId,
|
|
50
61
|
});
|
|
51
62
|
|
|
52
63
|
// 4. Webhooks: verify the signature on the raw request body.
|
|
53
|
-
const event = lynkoria.webhooks.verify(rawBody,
|
|
64
|
+
const event = lynkoria.webhooks.verify(rawBody, request.headers.get('lynkoria-signature'));
|
|
54
65
|
```
|
|
55
66
|
|
|
56
|
-
Return
|
|
67
|
+
Return the join credentials and `messagingToken` to your app, which passes them to
|
|
57
68
|
[`@lynkoria/client`](https://www.npmjs.com/package/@lynkoria/client) or a native SDK.
|
|
58
69
|
|
|
59
70
|
## What it covers
|
|
60
71
|
|
|
61
|
-
| Area | Methods
|
|
62
|
-
| ------------- |
|
|
63
|
-
| Calls | `calls.create`, `get`, `joinToken`, `end`, `removeParticipant`, `setRole`, `signal`
|
|
64
|
-
| Messaging | `sessions.messagingToken
|
|
65
|
-
| Users | `users.suspend`, `unsuspend`
|
|
66
|
-
|
|
|
67
|
-
|
|
|
68
|
-
|
|
|
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/) |
|
|
69
81
|
|
|
70
82
|
The full method list is in the [server SDK reference](https://lynkoria.com/docs/server-sdk/).
|
|
71
83
|
|
|
72
84
|
## Errors and delivery
|
|
73
85
|
|
|
74
86
|
Failed calls throw `LynkoriaError` with `code`, `status` and `requestId`; see [errors](https://lynkoria.com/docs/errors/).
|
|
75
|
-
|
|
87
|
+
Idempotent operations retry network errors, 429, 502, 503 and 504 with backoff (`maxRetries`, default 2).
|
|
88
|
+
Webhooks are delivered at least once, so deduplicate by `event.id`. When you rotate the webhook secret in
|
|
89
|
+
the console, deliveries are signed with both the old and the new secret for 24 hours, so you can deploy
|
|
90
|
+
the new one without missing events.
|
|
91
|
+
|
|
92
|
+
## Keep the service key on the server
|
|
93
|
+
|
|
94
|
+
`createLynkoriaServer` throws in a browser or React Native app, where the service key would reach every
|
|
95
|
+
user. Mint tokens on your backend and use [`@lynkoria/client`](https://www.npmjs.com/package/@lynkoria/client)
|
|
96
|
+
in the app.
|
|
76
97
|
|
|
77
98
|
## Related packages
|
|
78
99
|
|
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
|
-
import { Call, CallSignalRequest, Conversation, CreateCallRequest, CreateConversationRequest, ErrorCode, JoinTokenRequest, JoinTokenResponse, LynkoriaError, MessagingTokenRequest, MessagingTokenResponse, ParticipantRole, Recording, RecordingDownload, 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
|
+
/** The Lynkoria API. */
|
|
4
|
+
export declare const DEFAULT_API_URL = "https://api.lynkoria.com";
|
|
3
5
|
export type LynkoriaServerOptions = {
|
|
4
|
-
/**
|
|
5
|
-
baseUrl
|
|
6
|
+
/** Overrides the API origin ({@link DEFAULT_API_URL}); for local development and tests. */
|
|
7
|
+
baseUrl?: string;
|
|
6
8
|
/** `lynk_live_…` / `lynk_test_…` from your secret manager. Never ship it to a client. */
|
|
7
9
|
serviceKey: string;
|
|
8
10
|
/** Signing secret for verifying Lynkoria webhooks (`whsec_…`). Pass several during rotation. */
|
|
@@ -25,21 +27,87 @@ export type LynkoriaServer = {
|
|
|
25
27
|
}): Promise<JoinTokenResponse>;
|
|
26
28
|
end(callId: string): Promise<Call>;
|
|
27
29
|
removeParticipant(callId: string, identity: string): Promise<void>;
|
|
30
|
+
/**
|
|
31
|
+
* Disconnects every device of `userId`; resolves with how many were connected. An unused join
|
|
32
|
+
* token stays valid until it expires, so also stop issuing tokens to the user.
|
|
33
|
+
*/
|
|
34
|
+
removeUser(callId: string, userId: string): Promise<RemoveUserResponse>;
|
|
28
35
|
setRole(callId: string, identity: string, role: ParticipantRole): Promise<void>;
|
|
29
36
|
signal(callId: string, input: CallSignalRequest): Promise<void>;
|
|
30
37
|
};
|
|
31
38
|
sessions: {
|
|
32
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>;
|
|
33
48
|
};
|
|
34
49
|
users: {
|
|
35
50
|
suspend(userId: string): Promise<void>;
|
|
36
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
|
+
}>;
|
|
37
64
|
};
|
|
38
65
|
conversations: {
|
|
39
66
|
create(input: CreateConversationRequest): Promise<Conversation>;
|
|
40
|
-
|
|
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>;
|
|
41
79
|
removeMember(conversationId: string, userId: string): Promise<void>;
|
|
42
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
|
+
};
|
|
43
111
|
notifications: {
|
|
44
112
|
/** Queues push notifications to users' registered devices; resolves with the queued count. */
|
|
45
113
|
send(input: SendNotificationRequest): Promise<SendNotificationResponse>;
|
|
@@ -59,6 +127,8 @@ export type LynkoriaServer = {
|
|
|
59
127
|
};
|
|
60
128
|
};
|
|
61
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[][];
|
|
62
132
|
/** Standalone verifier: `t=<unix>,v1=<hex HMAC-SHA256(secret, "<t>.<rawBody>")>`; rejects stale timestamps. */
|
|
63
133
|
export declare function verifyWebhook<T = Record<string, unknown>>(rawBody: string, header: string | null | undefined, secrets: string[], nowSeconds?: number): WebhookEvent<T>;
|
|
64
134
|
export { ErrorCode, LynkoriaError, WEBHOOK_SIGNATURE_HEADER };
|
package/dist/index.js
CHANGED
|
@@ -1,10 +1,18 @@
|
|
|
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
|
+
/** The Lynkoria API. */
|
|
5
|
+
const DEFAULT_API_URL = "https://api.lynkoria.com";
|
|
4
6
|
const enc = encodeURIComponent;
|
|
7
|
+
/** True in a browser or React Native, where a service key would ship to every user. */
|
|
8
|
+
function isClientRuntime() {
|
|
9
|
+
const g = globalThis;
|
|
10
|
+
return typeof g.window !== "undefined" && typeof g.document !== "undefined" || g.navigator?.product === "ReactNative";
|
|
11
|
+
}
|
|
5
12
|
function createLynkoriaServer(opts) {
|
|
6
|
-
if (
|
|
7
|
-
|
|
13
|
+
if (isClientRuntime()) throw new Error("@lynkoria/server must run on your backend: a service key in a browser or mobile app is exposed to every user. Mint tokens on the server and use @lynkoria/client in the app.");
|
|
14
|
+
if (!/^lynk_(live|test)_/.test(opts.serviceKey ?? "")) throw new Error("serviceKey must be a lynk_live_ or lynk_test_ key (is LYNKORIA_SERVICE_KEY set on the server?)");
|
|
15
|
+
const base = (opts.baseUrl || "https://api.lynkoria.com").replace(/\/+$/, "");
|
|
8
16
|
const doFetch = opts.fetch ?? fetch;
|
|
9
17
|
const timeoutMs = opts.timeoutMs ?? 1e4;
|
|
10
18
|
const maxRetries = Math.max(0, opts.maxRetries ?? 2);
|
|
@@ -43,7 +51,8 @@ function createLynkoriaServer(opts) {
|
|
|
43
51
|
}
|
|
44
52
|
if (!res.ok) {
|
|
45
53
|
const error = LynkoriaError$1.fromBody(res.status, json);
|
|
46
|
-
const
|
|
54
|
+
const header = res.headers.get("retry-after");
|
|
55
|
+
const retryAfter = header === null || header.trim() === "" ? NaN : Number(header);
|
|
47
56
|
if (Number.isFinite(retryAfter) && retryAfter >= 0) retryAfterSeconds.set(error, retryAfter);
|
|
48
57
|
throw error;
|
|
49
58
|
}
|
|
@@ -57,19 +66,84 @@ function createLynkoriaServer(opts) {
|
|
|
57
66
|
joinToken: ({ callId, ...input }) => idempotent("POST", `/v1/calls/${enc(callId)}/join-token`, input),
|
|
58
67
|
end: (callId) => idempotent("POST", `/v1/calls/${enc(callId)}/end`),
|
|
59
68
|
removeParticipant: (callId, identity) => idempotent("POST", `/v1/calls/${enc(callId)}/participants/${enc(identity)}/remove`),
|
|
69
|
+
removeUser: (callId, userId) => idempotent("POST", `/v1/calls/${enc(callId)}/users/${enc(userId)}/remove`),
|
|
60
70
|
setRole: (callId, identity, role) => idempotent("POST", `/v1/calls/${enc(callId)}/participants/${enc(identity)}/permissions`, { role }),
|
|
61
71
|
signal: (callId, input) => request("POST", `/v1/calls/${enc(callId)}/signal`, input)
|
|
62
72
|
},
|
|
63
|
-
sessions: {
|
|
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
|
+
},
|
|
64
77
|
users: {
|
|
65
78
|
suspend: (userId) => idempotent("POST", `/v1/users/${enc(userId)}/suspend`),
|
|
66
|
-
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)}`)
|
|
67
82
|
},
|
|
68
83
|
conversations: {
|
|
69
84
|
create: (input) => request("POST", "/v1/conversations", input),
|
|
70
|
-
|
|
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 }),
|
|
71
99
|
removeMember: (id, userId) => request("DELETE", `/v1/conversations/${enc(id)}/members/${enc(userId)}`)
|
|
72
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
|
+
},
|
|
73
147
|
notifications: { send: (input) => request("POST", "/v1/notifications", input) },
|
|
74
148
|
recordings: {
|
|
75
149
|
start: (callId, input) => request("POST", `/v1/calls/${enc(callId)}/recordings`, input),
|
|
@@ -82,6 +156,27 @@ function createLynkoriaServer(opts) {
|
|
|
82
156
|
webhooks: { verify: (rawBody, header, nowSeconds) => verifyWebhook(rawBody, header, secrets, nowSeconds) }
|
|
83
157
|
};
|
|
84
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
|
+
}
|
|
85
180
|
const retryAfterSeconds = /* @__PURE__ */ new WeakMap();
|
|
86
181
|
const RETRYABLE_STATUS = /* @__PURE__ */ new Set([
|
|
87
182
|
429,
|
|
@@ -115,4 +210,4 @@ function verifyWebhook(rawBody, header, secrets, nowSeconds = Math.floor(Date.no
|
|
|
115
210
|
})) throw new LynkoriaError$1(ErrorCode$1.Unauthorized, "Invalid webhook signature");
|
|
116
211
|
return JSON.parse(rawBody);
|
|
117
212
|
}
|
|
118
|
-
export { 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.
|
|
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.
|
|
29
|
+
"@lynkoria/contracts": "^0.4.0"
|
|
30
30
|
},
|
|
31
31
|
"devDependencies": {
|
|
32
32
|
"@lynkoria/config": "0.0.0",
|