@beesolve/realtime-server 0.0.0 → 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/DOCS.md ADDED
@@ -0,0 +1,24 @@
1
+ # @beesolve/realtime-server - Documentation
2
+
3
+ **Keywords:** realtime, IoT Core, MQTT, WebSocket, CloudFront, CDK, Realtime, RealtimeProps, RealtimeAuthorizerFunction, addToDistribution, grantPublish, RealtimeLogging, RealtimeLoggingProps, RealtimeLogLevel, RealtimeLogEventLevel, RealtimeLogEventOverride, createRealtimeAuthorizerHandler, RealtimeAuthorize, RealtimeAuthorizeRequest, RealtimeAuthorizeResult, IotCustomAuthorizerEvent, IotCustomAuthorizerResult, custom authorizer, createRealtimePublisher, RealtimePublisher, RealtimePublisherProps, RealtimePublisherClient, RealtimeTarget, publish, broadcast, userId, group, refreshAfter, maxConnectionDuration, scope, policy, logging, AWSIotLogsV2, log group already exists, cost, limits
4
+
5
+ > This documentation is published inside the installed package and matches the installed version. Prefer it over prior knowledge or older examples found online.
6
+
7
+ > Full source and examples: https://github.com/BeeSolve/packages/tree/main/packages/realtime-server
8
+
9
+ ## How-To Guides
10
+
11
+ | Guide | Description |
12
+ | --------------------------------------------------------- | ------------------------------------------------------------ |
13
+ | [Getting Started](./docs/how-to/getting-started.md) | CDK, auth-service authorizer, publish, subscribe |
14
+ | [Custom Authorizer](./docs/how-to/custom-authorizer.md) | A JWT authorizer built with createRealtimeAuthorizerHandler |
15
+ | [Delivery Semantics](./docs/how-to/delivery-semantics.md) | Best effort, revocation latency, session rotation reconnects |
16
+ | [Logging](./docs/how-to/logging.md) | Opt-in IoT logging, fixing "AWSIotLogsV2 already exists" |
17
+ | [Limits](./docs/how-to/limits.md) | Channels, payload, policy and account limits |
18
+
19
+ ## Further Reading
20
+
21
+ - [README](./README.md) - API reference, configuration and cost
22
+ - [CHANGELOG](./CHANGELOG.md) - Version history
23
+ - [@beesolve/auth-service realtime guide](https://github.com/BeeSolve/packages/tree/main/packages/service-auth/docs/how-to/realtime.md)
24
+ - [Architecture Decision Records](https://github.com/BeeSolve/packages/tree/main/packages/realtime-server/docs) (GitHub only)
package/README.md CHANGED
@@ -1,4 +1,127 @@
1
- # Placeholder Package
1
+ # Realtime Server
2
2
 
3
- Published at `0.0.0` to reserve the npm name and configure CI publish (OIDC Trusted Publisher)
4
- permissions. The real package is released from the @beesolve/packages monorepo via changesets.
3
+ AWS IoT Core behind your CloudFront distribution for server-to-browser realtime updates: a CDK construct, a pluggable custom authorizer handler and a scoped publisher.
4
+
5
+ > [!WARNING]
6
+ > **Pre-1.0 - unstable API.** This package is `0.x` and under active
7
+ > development. Breaking changes can land in any `0.x` release without a major
8
+ > version bump. Pin an exact version and review the changelog before upgrading.
9
+ > Once the API stabilizes and the package reaches `1.0.0`, it follows semantic
10
+ > versioning and this notice is removed.
11
+
12
+ ## Installation
13
+
14
+ ```bash
15
+ bun add @beesolve/realtime-server @beesolve/realtime-core
16
+ ```
17
+
18
+ (or `npm install @beesolve/realtime-server @beesolve/realtime-core`)
19
+
20
+ `@aws-sdk/client-iot-data-plane`, `aws-cdk-lib` (2.278.0 or newer) and `constructs` are peer dependencies.
21
+
22
+ ## Quick Start
23
+
24
+ CDK, with the session-cookie authorizer from `@beesolve/auth-service`:
25
+
26
+ ```ts
27
+ import { AuthService } from "@beesolve/auth-service/cdk";
28
+ import { Realtime } from "@beesolve/realtime-server/cdk";
29
+
30
+ const realtime = new Realtime(this, "Realtime", {
31
+ scope: "myapp-dev",
32
+ authorizer: auth.createRealtimeAuthorizer(this, "RealtimeAuthorizer"),
33
+ });
34
+ realtime.addToDistribution(distribution);
35
+ realtime.grantPublish(appFunction);
36
+ ```
37
+
38
+ Publish from the Lambda:
39
+
40
+ ```ts
41
+ import { createRealtimePublisher } from "@beesolve/realtime-server/publish";
42
+
43
+ const publisher = createRealtimePublisher();
44
+ await publisher.publish({ channel: orderPaid, to: { userId }, payload: { orderId, amount } });
45
+ ```
46
+
47
+ Subscribe in the browser with `@beesolve/realtime-client`.
48
+
49
+ ## API
50
+
51
+ ### `@beesolve/realtime-server/cdk`
52
+
53
+ | Export | Description |
54
+ | ----------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ |
55
+ | `Realtime` | Construct: IoT endpoint lookup, custom authorizer, CloudFront WebSocket behavior, publish grant. |
56
+ | `RealtimeProps` | Props of `Realtime`. |
57
+ | `RealtimeAuthorizerFunction` | `{ handler: IFunction, cookies: string[] }`. `handler` must be a `Function`. |
58
+ | `RealtimeLogging` | Opt-in IoT v2 logging. See the logging guide. |
59
+ | `RealtimeLoggingProps`, `RealtimeLogLevel`, `RealtimeLogEventLevel`, `RealtimeLogEventOverride` | Logging types. |
60
+
61
+ `RealtimeProps`:
62
+
63
+ | Prop | Default | Description |
64
+ | ----------------------- | --------- | ----------------------------------------------------------------------- |
65
+ | `scope` | required | Topic prefix per app and stage. `[A-Za-z0-9_-]{1,128}`. |
66
+ | `authorizer` | required | `RealtimeAuthorizerFunction`. |
67
+ | `path` | `"/mqtt"` | CloudFront path pattern of the WebSocket behavior. |
68
+ | `refreshAfter` | 1 hour | How often IoT re-runs the authorizer. Clamped to 5 minutes to 24 hours. |
69
+ | `maxConnectionDuration` | 24 hours | Maximum connection lifetime. Clamped to 5 minutes to 24 hours. |
70
+
71
+ `Realtime` members: `endpoint` (IoT data host, a token), `authorizerName`, `scope`, `addToDistribution(distribution)` (call once), `grantPublish(fn)` (allows `iot:Publish` on `topic/<scope>/*` and sets `BEESOLVE_REALTIME_ENDPOINT` and `BEESOLVE_REALTIME_SCOPE`). The construct sets `BEESOLVE_REALTIME_SCOPE`, `BEESOLVE_REALTIME_REFRESH_SECONDS` and `BEESOLVE_REALTIME_MAX_CONNECTION_SECONDS` on the authorizer function. Create one `Realtime` per app and stage: an account has at most 32 active custom authorizers.
72
+
73
+ ### `@beesolve/realtime-server/authorizer`
74
+
75
+ | Export | Description |
76
+ | -------------------------------------------------------------------------- | --------------------------------------------------------------- |
77
+ | `createRealtimeAuthorizerHandler(authorize)` | Returns the Lambda handler. Builds policies and clamps timings. |
78
+ | `RealtimeAuthorize`, `RealtimeAuthorizeRequest`, `RealtimeAuthorizeResult` | The `authorize` contract. |
79
+ | `IotCustomAuthorizerEvent`, `IotCustomAuthorizerResult` | IoT event and response shapes. |
80
+
81
+ ### `@beesolve/realtime-server/publish`
82
+
83
+ | Export | Description |
84
+ | ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
85
+ | `createRealtimePublisher(props?)` | Returns a `RealtimePublisher`. `endpoint` and `scope` default to the environment variables. |
86
+ | `RealtimePublisher.publish({ channel, to, payload })` | Validates, then publishes with QoS 1 to each target group. Throws `AggregateError` if any topic fails. Payloads over 128 KB throw. |
87
+ | `RealtimeTarget` | `{ userId }`, `{ userIds }`, `{ group }` or `{ broadcast: true }`. |
88
+ | `RealtimePublisherProps`, `RealtimePublisherClient` | Props (`endpoint`, `scope`, `client`) and the client interface for tests. |
89
+
90
+ ## Cost
91
+
92
+ Estimated for `eu-central-1` list prices from the AWS Pricing API, taken in November 2026. Prices change, so treat this section as an estimate and check the current pages.
93
+
94
+ | Item | Price |
95
+ | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
96
+ | IoT connectivity | $0.096 per million connection-minutes |
97
+ | IoT messaging | $1.20 per million messages (first 1B), metered in 5 KB increments. A publish counts once inbound and once per delivered connection. Pings at 30s or more are free. |
98
+ | Lambda authorizer | Runs on connect and on each refresh while traffic flows, plus one DynamoDB GetItem |
99
+ | CloudFront | 1 request per connection, plus data out for frames |
100
+ | IoT logs | CloudWatch ingestion, about 400 B per event at INFO |
101
+
102
+ Example: 1,000 users, each connected 8 hours a day for 22 days, receiving 20 personal and 10 broadcast messages a day, with QoS 0:
103
+
104
+ | Item | Monthly cost |
105
+ | ----------------------- | -------------------------- |
106
+ | Connectivity | 10.6M minutes, about $1.01 |
107
+ | Messages | 1.1M, about $1.32 |
108
+ | Authorizer and DynamoDB | about $0.15 |
109
+ | CloudFront | about $0.10 |
110
+ | Logs at ERROR | about $0 |
111
+ | **Total** | **about $2.60** |
112
+
113
+ Cost scales linearly with users. Double the users and the total roughly doubles.
114
+
115
+ Cost levers:
116
+
117
+ - **Keepalive of 30s or more.** Pings at 30s or more are not billed. The client default is 60s and it refuses less than 30s.
118
+ - **QoS 0 subscriptions.** With QoS 1 the client's PUBACK may be metered as an extra message, so QoS 0 can halve outbound messaging cost. This is the client default.
119
+ - **`refreshAfter`.** Each refresh is one authorizer run per active connection. A shorter interval revokes sooner and costs more.
120
+ - **Log level.** INFO logs every publish in and out and adds about 30%. Keep ERROR unless you debug.
121
+
122
+ Pricing pages: [AWS IoT Core pricing](https://aws.amazon.com/iot-core/pricing/), [AWS IoT Core metering details](https://docs.aws.amazon.com/iot/latest/developerguide/metering-details.html) and [Amazon CloudFront pricing](https://aws.amazon.com/cloudfront/pricing/).
123
+
124
+ ## Further Reading
125
+
126
+ - [DOCS.md](./DOCS.md) - Agent-oriented index
127
+ - [Architecture Decision Records](https://github.com/BeeSolve/packages/tree/main/packages/realtime-server/docs) (GitHub only)
@@ -0,0 +1,52 @@
1
+ import { Context, PolicyDocument } from "aws-lambda";
2
+ interface RealtimeAuthorizeRequest {
3
+ readonly headers: Headers;
4
+ readonly query: URLSearchParams;
5
+ readonly clientId: string;
6
+ }
7
+ type RealtimeAuthorizeResult = {
8
+ readonly type: "allow";
9
+ readonly userId: string;
10
+ /** Extra groups beyond the user's own group and broadcast. */
11
+ readonly groups?: ReadonlyArray<string>;
12
+ /** Connection is closed at the earlier of this and the max connection duration. */
13
+ readonly expiresAt?: Date;
14
+ } | {
15
+ readonly type: "deny";
16
+ readonly reason: string;
17
+ };
18
+ type RealtimeAuthorize = (request: RealtimeAuthorizeRequest) => Promise<RealtimeAuthorizeResult>;
19
+ /** The event IoT Core sends to a custom authorizer Lambda. */
20
+ interface IotCustomAuthorizerEvent {
21
+ readonly protocolData?: {
22
+ readonly http?: {
23
+ readonly headers?: Record<string, string>;
24
+ readonly queryString?: string;
25
+ };
26
+ readonly mqtt?: {
27
+ readonly clientId?: string;
28
+ readonly username?: string;
29
+ readonly password?: string;
30
+ };
31
+ };
32
+ readonly protocols?: ReadonlyArray<string>;
33
+ readonly signatureVerified?: boolean;
34
+ readonly connectionMetadata?: {
35
+ readonly id?: string;
36
+ };
37
+ }
38
+ /** The response IoT Core expects from a custom authorizer Lambda. */
39
+ interface IotCustomAuthorizerResult {
40
+ readonly isAuthenticated: boolean;
41
+ readonly principalId: string;
42
+ readonly policyDocuments: Array<PolicyDocument>;
43
+ readonly disconnectAfterInSeconds: number;
44
+ readonly refreshAfterInSeconds: number;
45
+ }
46
+ /**
47
+ * Creates the Lambda handler for the IoT custom authorizer. `authorize` answers who the caller
48
+ * is, which extra groups they get and until when. Policy building, id validation and timing
49
+ * clamps are handled here.
50
+ */
51
+ declare function createRealtimeAuthorizerHandler(authorize: RealtimeAuthorize): (event: IotCustomAuthorizerEvent, context: Context) => Promise<IotCustomAuthorizerResult>;
52
+ export { IotCustomAuthorizerEvent, IotCustomAuthorizerResult, RealtimeAuthorize, RealtimeAuthorizeRequest, RealtimeAuthorizeResult, createRealtimeAuthorizerHandler };
@@ -0,0 +1,116 @@
1
+ import {
2
+ parseAuthorizerEnv
3
+ } from "./shared/@beesolve/realtime-server-bhn5bx3r.js";
4
+
5
+ // packages/realtime-server/authorizer.ts
6
+ import { broadcastGroup, isTopicSafeId } from "@beesolve/realtime-core";
7
+
8
+ // packages/realtime-server/src/policy.ts
9
+ var maxPolicyDocuments = 10;
10
+ var maxPolicyDocumentLength = 2048;
11
+ function buildPolicyDocuments(props) {
12
+ const prefix = `arn:aws:iot:${props.region}:${props.account}:`;
13
+ const drafts = [
14
+ {
15
+ base: [
16
+ statement("iot:Connect", ["*"]),
17
+ statement("iot:Subscribe", [`${prefix}topicfilter/${props.scope}/*`])
18
+ ],
19
+ receive: []
20
+ }
21
+ ];
22
+ for (const group of props.groups) {
23
+ const resource = `${prefix}topic/${props.scope}/${group}/*`;
24
+ const target = drafts.find((draft) => fits(draft, resource));
25
+ if (target != null) {
26
+ target.receive.push(resource);
27
+ continue;
28
+ }
29
+ const created = { base: [], receive: [] };
30
+ if (drafts.length >= maxPolicyDocuments || !fits(created, resource))
31
+ return null;
32
+ created.receive.push(resource);
33
+ drafts.push(created);
34
+ }
35
+ return drafts.map(toDocument);
36
+ }
37
+ function fits(draft, resource) {
38
+ const candidate = toDocument({ base: draft.base, receive: [...draft.receive, resource] });
39
+ return JSON.stringify(candidate).length <= maxPolicyDocumentLength;
40
+ }
41
+ function toDocument(draft) {
42
+ const statements = [...draft.base];
43
+ if (draft.receive.length > 0) {
44
+ statements.push(statement("iot:Receive", draft.receive));
45
+ }
46
+ return { Version: "2012-10-17", Statement: statements };
47
+ }
48
+ function statement(action, resources) {
49
+ return { Effect: "Allow", Action: [action], Resource: [...resources] };
50
+ }
51
+
52
+ // packages/realtime-server/authorizer.ts
53
+ var minSeconds = 300;
54
+ var maxSeconds = 86400;
55
+ function createRealtimeAuthorizerHandler(authorize) {
56
+ const env = parseAuthorizerEnv(process.env);
57
+ return async (event, context) => {
58
+ const refreshAfterInSeconds = clamp(env.refreshSeconds);
59
+ const deny = (reason) => {
60
+ console.log(JSON.stringify({ msg: "realtime-authorizer-deny", reason }));
61
+ return {
62
+ isAuthenticated: false,
63
+ principalId: "anonymous",
64
+ policyDocuments: [],
65
+ disconnectAfterInSeconds: minSeconds,
66
+ refreshAfterInSeconds
67
+ };
68
+ };
69
+ let result;
70
+ try {
71
+ result = await authorize(toRequest(event));
72
+ } catch (error) {
73
+ return deny(`authorize threw: ${error instanceof Error ? error.message : String(error)}`);
74
+ }
75
+ if (result.type === "deny")
76
+ return deny(result.reason);
77
+ const extraGroups = result.groups ?? [];
78
+ const invalid = [result.userId, ...extraGroups].find((id) => !isTopicSafeId(id));
79
+ if (invalid != null)
80
+ return deny("invalid userId or group id");
81
+ const groups = [...new Set([result.userId, broadcastGroup, ...extraGroups])];
82
+ const policyDocuments = buildPolicyDocuments({
83
+ scope: env.scope,
84
+ region: process.env.AWS_REGION ?? context.invokedFunctionArn.split(":")[3] ?? "*",
85
+ account: context.invokedFunctionArn.split(":")[4] ?? "*",
86
+ groups
87
+ });
88
+ if (policyDocuments == null)
89
+ return deny("too many groups");
90
+ return {
91
+ isAuthenticated: true,
92
+ principalId: toPrincipalId(result.userId),
93
+ policyDocuments,
94
+ disconnectAfterInSeconds: clamp(Math.min(env.maxConnectionSeconds, result.expiresAt == null ? Number.POSITIVE_INFINITY : Math.floor((result.expiresAt.getTime() - Date.now()) / 1000))),
95
+ refreshAfterInSeconds
96
+ };
97
+ };
98
+ }
99
+ function toRequest(event) {
100
+ const http = event.protocolData?.http;
101
+ return {
102
+ headers: new Headers(http?.headers ?? {}),
103
+ query: new URLSearchParams(http?.queryString ?? ""),
104
+ clientId: event.protocolData?.mqtt?.clientId ?? ""
105
+ };
106
+ }
107
+ function clamp(seconds) {
108
+ return Math.min(maxSeconds, Math.max(minSeconds, Math.floor(seconds)));
109
+ }
110
+ function toPrincipalId(userId) {
111
+ const stripped = userId.replace(/[^a-zA-Z0-9]/g, "").slice(0, 128);
112
+ return stripped === "" ? "anonymous" : stripped;
113
+ }
114
+ export {
115
+ createRealtimeAuthorizerHandler
116
+ };
package/dist/cdk.d.ts ADDED
@@ -0,0 +1,77 @@
1
+ import { Duration } from "aws-cdk-lib";
2
+ import { Distribution } from "aws-cdk-lib/aws-cloudfront";
3
+ import { IFunction } from "aws-cdk-lib/aws-lambda";
4
+ import { Function as LambdaFunction } from "aws-cdk-lib/aws-lambda";
5
+ import { Construct as Construct2 } from "constructs";
6
+ import { RetentionDays } from "aws-cdk-lib/aws-logs";
7
+ import { Construct } from "constructs";
8
+ type RealtimeLogLevel = "ERROR" | "WARN" | "INFO" | "DEBUG";
9
+ type RealtimeLogEventLevel = RealtimeLogLevel | "DISABLED";
10
+ interface RealtimeLogEventOverride {
11
+ readonly eventType: string;
12
+ readonly level: RealtimeLogEventLevel;
13
+ }
14
+ interface RealtimeLoggingProps {
15
+ /** Default log level for all IoT events. Defaults to `"ERROR"`. */
16
+ readonly level?: RealtimeLogLevel;
17
+ /** Retention of the `AWSIotLogsV2` log group. Defaults to two weeks. */
18
+ readonly retention?: RetentionDays;
19
+ /**
20
+ * Create the `AWSIotLogsV2` log group with retention before IoT can create it without one.
21
+ * Defaults to `true`.
22
+ */
23
+ readonly createLogGroup?: boolean;
24
+ /**
25
+ * Per event level overrides. IoT merges them per event and cannot clear them. AWS defaults
26
+ * `Connection.AuthNError` and `Ping` to `DISABLED`.
27
+ */
28
+ readonly eventOverrides?: ReadonlyArray<RealtimeLogEventOverride>;
29
+ }
30
+ /**
31
+ * Opt-in IoT v2 logging. IoT logging is a singleton per account and region, so create at most
32
+ * one per account and region. Deleting the construct disables IoT logging for the whole account
33
+ * and region.
34
+ */
35
+ declare class RealtimeLogging extends Construct {
36
+ readonly logGroupName: string;
37
+ constructor(scope: Construct, id: string, props?: RealtimeLoggingProps);
38
+ }
39
+ interface RealtimeAuthorizerFunction {
40
+ /**
41
+ * Lambda whose handler was built with `createRealtimeAuthorizerHandler`. It must be a
42
+ * `Function` so the construct can set its environment.
43
+ */
44
+ readonly handler: IFunction;
45
+ /** Cookie names the origin request policy forwards to IoT. */
46
+ readonly cookies: ReadonlyArray<string>;
47
+ }
48
+ interface RealtimeProps {
49
+ /** Per app and stage topic prefix. Must match `[A-Za-z0-9_-]{1,128}`. */
50
+ readonly scope: string;
51
+ readonly authorizer: RealtimeAuthorizerFunction;
52
+ /** CloudFront path pattern of the WebSocket behavior. Defaults to `"/mqtt"`. */
53
+ readonly path?: string;
54
+ /** How often IoT re-runs the authorizer. Clamped to 5m..24h, defaults to 1h. */
55
+ readonly refreshAfter?: Duration;
56
+ /** Maximum connection lifetime. Clamped to 5m..24h, defaults to 24h. */
57
+ readonly maxConnectionDuration?: Duration;
58
+ }
59
+ /**
60
+ * IoT Core WebSocket endpoint with a custom authorizer, reachable from a CloudFront
61
+ * distribution so the browser sends its HttpOnly session cookie on the handshake.
62
+ */
63
+ declare class Realtime extends Construct2 {
64
+ /** IoT data endpoint host name (token). */
65
+ readonly endpoint: string;
66
+ readonly authorizerName: string;
67
+ readonly scope: string;
68
+ private readonly path;
69
+ private readonly cookies;
70
+ private distributionAdded;
71
+ constructor(scope: Construct2, id: string, props: RealtimeProps);
72
+ /** Adds the WebSocket behavior to the distribution. Can be called once. */
73
+ addToDistribution(distribution: Distribution): void;
74
+ /** Allows the function to publish under the scope and sets the publisher env variables. */
75
+ grantPublish(fn: LambdaFunction): void;
76
+ }
77
+ export { Realtime, RealtimeAuthorizerFunction, RealtimeLogEventLevel, RealtimeLogEventOverride, RealtimeLogLevel, RealtimeLogging, RealtimeLoggingProps, RealtimeProps };
package/dist/cdk.js ADDED
@@ -0,0 +1,202 @@
1
+ // packages/realtime-server/cdk.ts
2
+ import { isTopicSafeId } from "@beesolve/realtime-core";
3
+ import { Duration, Names, RemovalPolicy as RemovalPolicy2, Stack as Stack2 } from "aws-cdk-lib";
4
+ import {
5
+ AllowedMethods,
6
+ CachePolicy,
7
+ Function as CloudFrontFunction,
8
+ FunctionCode,
9
+ FunctionEventType,
10
+ FunctionRuntime,
11
+ OriginProtocolPolicy,
12
+ OriginRequestCookieBehavior,
13
+ OriginRequestHeaderBehavior,
14
+ OriginRequestPolicy,
15
+ OriginRequestQueryStringBehavior,
16
+ ViewerProtocolPolicy
17
+ } from "aws-cdk-lib/aws-cloudfront";
18
+ import { HttpOrigin } from "aws-cdk-lib/aws-cloudfront-origins";
19
+ import { PolicyStatement as PolicyStatement2, ServicePrincipal as ServicePrincipal2 } from "aws-cdk-lib/aws-iam";
20
+ import { CfnAuthorizer } from "aws-cdk-lib/aws-iot";
21
+ import { Function as LambdaFunction } from "aws-cdk-lib/aws-lambda";
22
+ import { LogGroup as LogGroup2, RetentionDays as RetentionDays2 } from "aws-cdk-lib/aws-logs";
23
+ import {
24
+ AwsCustomResource as AwsCustomResource2,
25
+ AwsCustomResourcePolicy as AwsCustomResourcePolicy2,
26
+ PhysicalResourceId as PhysicalResourceId2
27
+ } from "aws-cdk-lib/custom-resources";
28
+ import { Construct as Construct2 } from "constructs";
29
+
30
+ // packages/realtime-server/src/logging.ts
31
+ import { RemovalPolicy, Stack } from "aws-cdk-lib";
32
+ import { Effect, PolicyStatement, Role, ServicePrincipal } from "aws-cdk-lib/aws-iam";
33
+ import { LogGroup, RetentionDays } from "aws-cdk-lib/aws-logs";
34
+ import {
35
+ AwsCustomResource,
36
+ AwsCustomResourcePolicy,
37
+ PhysicalResourceId
38
+ } from "aws-cdk-lib/custom-resources";
39
+ import { Construct } from "constructs";
40
+
41
+ class RealtimeLogging extends Construct {
42
+ logGroupName = "AWSIotLogsV2";
43
+ constructor(scope, id, props = {}) {
44
+ super(scope, id);
45
+ const { account, region } = Stack.of(this);
46
+ const role = new Role(this, "Role", { assumedBy: new ServicePrincipal("iot.amazonaws.com") });
47
+ role.addToPolicy(new PolicyStatement({
48
+ effect: Effect.ALLOW,
49
+ actions: ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"],
50
+ resources: [`arn:aws:logs:${region}:${account}:log-group:${this.logGroupName}:*`]
51
+ }));
52
+ const iotLogGroup = props.createLogGroup === false ? undefined : new LogGroup(this, "IotLogGroup", {
53
+ logGroupName: this.logGroupName,
54
+ retention: props.retention ?? RetentionDays.TWO_WEEKS,
55
+ removalPolicy: RemovalPolicy.DESTROY
56
+ });
57
+ const eventConfigurations = props.eventOverrides?.map((override) => ({
58
+ eventType: override.eventType,
59
+ logLevel: override.level
60
+ }));
61
+ const call = {
62
+ service: "Iot",
63
+ action: "setV2LoggingOptions",
64
+ physicalResourceId: PhysicalResourceId.of("beesolve-realtime-logging"),
65
+ parameters: {
66
+ roleArn: role.roleArn,
67
+ defaultLogLevel: props.level ?? "ERROR",
68
+ ...eventConfigurations == null ? {} : { eventConfigurations }
69
+ }
70
+ };
71
+ const logging = new AwsCustomResource(this, "Logging", {
72
+ onCreate: call,
73
+ onUpdate: call,
74
+ onDelete: {
75
+ service: "Iot",
76
+ action: "setV2LoggingOptions",
77
+ physicalResourceId: PhysicalResourceId.of("beesolve-realtime-logging"),
78
+ parameters: { disableAllLogs: true }
79
+ },
80
+ installLatestAwsSdk: false,
81
+ policy: AwsCustomResourcePolicy.fromStatements([
82
+ new PolicyStatement({ actions: ["iot:SetV2LoggingOptions"], resources: ["*"] }),
83
+ new PolicyStatement({ actions: ["iam:PassRole"], resources: [role.roleArn] })
84
+ ]),
85
+ logGroup: new LogGroup(this, "LoggingLogs", {
86
+ retention: RetentionDays.ONE_WEEK,
87
+ removalPolicy: RemovalPolicy.DESTROY
88
+ })
89
+ });
90
+ logging.node.addDependency(role);
91
+ if (iotLogGroup != null)
92
+ logging.node.addDependency(iotLogGroup);
93
+ }
94
+ }
95
+
96
+ // packages/realtime-server/cdk.ts
97
+ var minSeconds = 300;
98
+ var maxSeconds = 86400;
99
+
100
+ class Realtime extends Construct2 {
101
+ endpoint;
102
+ authorizerName;
103
+ scope;
104
+ path;
105
+ cookies;
106
+ distributionAdded = false;
107
+ constructor(scope, id, props) {
108
+ super(scope, id);
109
+ if (!isTopicSafeId(props.scope)) {
110
+ throw new Error(`Invalid realtime scope "${props.scope}", expected [A-Za-z0-9_-]{1,128}`);
111
+ }
112
+ if (!(props.authorizer.handler instanceof LambdaFunction)) {
113
+ throw new Error("Realtime authorizer handler must be an aws-lambda Function");
114
+ }
115
+ this.scope = props.scope;
116
+ this.path = props.path ?? "/mqtt";
117
+ this.cookies = [...new Set(props.authorizer.cookies)];
118
+ const endpointCall = {
119
+ service: "Iot",
120
+ action: "describeEndpoint",
121
+ physicalResourceId: PhysicalResourceId2.of("beesolve-realtime-endpoint"),
122
+ parameters: { endpointType: "iot:Data-ATS" }
123
+ };
124
+ const endpoint = new AwsCustomResource2(this, "Endpoint", {
125
+ onCreate: endpointCall,
126
+ onUpdate: endpointCall,
127
+ installLatestAwsSdk: false,
128
+ policy: AwsCustomResourcePolicy2.fromSdkCalls({
129
+ resources: AwsCustomResourcePolicy2.ANY_RESOURCE
130
+ }),
131
+ logGroup: new LogGroup2(this, "EndpointLogs", {
132
+ retention: RetentionDays2.ONE_DAY,
133
+ removalPolicy: RemovalPolicy2.DESTROY
134
+ })
135
+ });
136
+ this.endpoint = endpoint.getResponseField("endpointAddress");
137
+ const handler = props.authorizer.handler;
138
+ handler.addEnvironment("BEESOLVE_REALTIME_SCOPE", props.scope);
139
+ handler.addEnvironment("BEESOLVE_REALTIME_REFRESH_SECONDS", String(clampSeconds(props.refreshAfter ?? Duration.hours(1))));
140
+ handler.addEnvironment("BEESOLVE_REALTIME_MAX_CONNECTION_SECONDS", String(clampSeconds(props.maxConnectionDuration ?? Duration.hours(24))));
141
+ this.authorizerName = Names.uniqueResourceName(this, { maxLength: 128 });
142
+ const cfnAuthorizer = new CfnAuthorizer(this, "Authorizer", {
143
+ authorizerName: this.authorizerName,
144
+ authorizerFunctionArn: handler.functionArn,
145
+ signingDisabled: true,
146
+ enableCachingForHttp: false,
147
+ status: "ACTIVE"
148
+ });
149
+ handler.addPermission("AllowIot", {
150
+ principal: new ServicePrincipal2("iot.amazonaws.com"),
151
+ sourceArn: cfnAuthorizer.attrArn
152
+ });
153
+ }
154
+ addToDistribution(distribution) {
155
+ if (this.distributionAdded) {
156
+ throw new Error("Realtime.addToDistribution can only be called once");
157
+ }
158
+ this.distributionAdded = true;
159
+ const setAuthorizerName = new CloudFrontFunction(this, "SetAuthorizerName", {
160
+ runtime: FunctionRuntime.JS_2_0,
161
+ code: FunctionCode.fromInline(`function handler(event) {
162
+ var request = event.request;
163
+ request.querystring = { "x-amz-customauthorizer-name": { value: ${JSON.stringify(this.authorizerName)} } };
164
+ return request;
165
+ }`)
166
+ });
167
+ const originRequestPolicy = new OriginRequestPolicy(this, "OriginRequestPolicy", {
168
+ cookieBehavior: OriginRequestCookieBehavior.allowList(...this.cookies),
169
+ headerBehavior: OriginRequestHeaderBehavior.allowList("Sec-WebSocket-Key", "Sec-WebSocket-Version", "Sec-WebSocket-Protocol", "Sec-WebSocket-Extensions"),
170
+ queryStringBehavior: OriginRequestQueryStringBehavior.allowList("x-amz-customauthorizer-name")
171
+ });
172
+ distribution.addBehavior(this.path, new HttpOrigin(this.endpoint, {
173
+ protocolPolicy: OriginProtocolPolicy.HTTPS_ONLY,
174
+ readTimeout: Duration.seconds(60),
175
+ keepaliveTimeout: Duration.seconds(60)
176
+ }), {
177
+ allowedMethods: AllowedMethods.ALLOW_ALL,
178
+ viewerProtocolPolicy: ViewerProtocolPolicy.HTTPS_ONLY,
179
+ cachePolicy: CachePolicy.CACHING_DISABLED,
180
+ originRequestPolicy,
181
+ functionAssociations: [
182
+ { function: setAuthorizerName, eventType: FunctionEventType.VIEWER_REQUEST }
183
+ ]
184
+ });
185
+ }
186
+ grantPublish(fn) {
187
+ const { account, region } = Stack2.of(this);
188
+ fn.addToRolePolicy(new PolicyStatement2({
189
+ actions: ["iot:Publish"],
190
+ resources: [`arn:aws:iot:${region}:${account}:topic/${this.scope}/*`]
191
+ }));
192
+ fn.addEnvironment("BEESOLVE_REALTIME_ENDPOINT", this.endpoint);
193
+ fn.addEnvironment("BEESOLVE_REALTIME_SCOPE", this.scope);
194
+ }
195
+ }
196
+ function clampSeconds(duration) {
197
+ return Math.min(maxSeconds, Math.max(minSeconds, duration.toSeconds()));
198
+ }
199
+ export {
200
+ Realtime,
201
+ RealtimeLogging
202
+ };
@@ -0,0 +1,42 @@
1
+ import { PublishCommand } from "@aws-sdk/client-iot-data-plane";
2
+ import { Channel } from "@beesolve/realtime-core";
3
+ import { StandardSchemaV1 } from "@standard-schema/spec";
4
+ /** Who receives a published message. */
5
+ type RealtimeTarget = {
6
+ readonly userId: string;
7
+ } | {
8
+ readonly userIds: ReadonlyArray<string>;
9
+ } | {
10
+ readonly group: string;
11
+ } | {
12
+ readonly broadcast: true;
13
+ };
14
+ /** The part of `IoTDataPlaneClient` the publisher uses. */
15
+ interface RealtimePublisherClient {
16
+ send(command: PublishCommand): Promise<unknown>;
17
+ }
18
+ interface RealtimePublisherProps {
19
+ /** IoT data endpoint host. Defaults to `BEESOLVE_REALTIME_ENDPOINT`. */
20
+ readonly endpoint?: string;
21
+ /** Topic scope. Defaults to `BEESOLVE_REALTIME_SCOPE`. */
22
+ readonly scope?: string;
23
+ readonly client?: RealtimePublisherClient;
24
+ }
25
+ interface RealtimePublisher {
26
+ /**
27
+ * Validates the payload against the channel schema, then publishes the validated output with
28
+ * QoS 1 to every target group. Throws an `AggregateError` listing the failed topics when any
29
+ * send fails; the other topics are still sent.
30
+ */
31
+ publish<TSchema extends StandardSchemaV1>(props: {
32
+ readonly channel: Channel<string, TSchema>;
33
+ readonly to: RealtimeTarget;
34
+ readonly payload: StandardSchemaV1.InferInput<TSchema>;
35
+ }): Promise<void>;
36
+ }
37
+ /**
38
+ * Creates a publisher. Endpoint and scope are read from the environment on the first publish,
39
+ * so importing this module never throws.
40
+ */
41
+ declare function createRealtimePublisher(props?: RealtimePublisherProps): RealtimePublisher;
42
+ export { RealtimePublisher, RealtimePublisherClient, RealtimePublisherProps, RealtimeTarget, createRealtimePublisher };
@@ -0,0 +1,63 @@
1
+ import {
2
+ parsePublisherEnv
3
+ } from "./shared/@beesolve/realtime-server-bhn5bx3r.js";
4
+
5
+ // packages/realtime-server/publish.ts
6
+ import { IoTDataPlaneClient, PublishCommand } from "@aws-sdk/client-iot-data-plane";
7
+ import { broadcastGroup, isTopicSafeId, parsePayload, toTopic } from "@beesolve/realtime-core";
8
+ var maxPayloadBytes = 128 * 1024;
9
+ function createRealtimePublisher(props = {}) {
10
+ let resolved;
11
+ function resolve() {
12
+ if (resolved != null)
13
+ return resolved;
14
+ const env = parsePublisherEnv(process.env);
15
+ const scope = props.scope ?? env.scope;
16
+ if (scope == null)
17
+ throw new Error("Missing realtime scope: set BEESOLVE_REALTIME_SCOPE");
18
+ const client = props.client ?? createClient(props.endpoint ?? env.endpoint);
19
+ resolved = { client, scope };
20
+ return resolved;
21
+ }
22
+ return {
23
+ async publish({ channel, to, payload }) {
24
+ const validated = await parsePayload({ schema: channel.schema, value: payload });
25
+ const body = JSON.stringify(validated);
26
+ const size = Buffer.byteLength(body);
27
+ if (size > maxPayloadBytes) {
28
+ throw new Error(`Payload is ${size} bytes, the maximum is ${maxPayloadBytes} bytes`);
29
+ }
30
+ const groups = resolveGroups(to);
31
+ const { client, scope } = resolve();
32
+ const topics = groups.map((group) => toTopic({ scope, group, channel: channel.name }));
33
+ const results = await Promise.allSettled(topics.map((topic) => client.send(new PublishCommand({ topic, payload: Buffer.from(body), qos: 1 }))));
34
+ const failures = results.flatMap((result, index) => result.status === "rejected" ? [{ topic: topics[index], reason: result.reason }] : []);
35
+ if (failures.length === 0)
36
+ return;
37
+ throw new AggregateError(failures.map((failure) => failure.reason), `Failed to publish to ${failures.length} of ${topics.length} topics: ${failures.map((failure) => failure.topic).join(", ")}`);
38
+ }
39
+ };
40
+ }
41
+ function createClient(endpoint) {
42
+ if (endpoint == null) {
43
+ throw new Error("Missing realtime endpoint: set BEESOLVE_REALTIME_ENDPOINT");
44
+ }
45
+ return new IoTDataPlaneClient({ endpoint: `https://${endpoint}` });
46
+ }
47
+ function resolveGroups(to) {
48
+ if ("broadcast" in to)
49
+ return [broadcastGroup];
50
+ if ("group" in to)
51
+ return [assertGroupId(to.group)];
52
+ if ("userId" in to)
53
+ return [assertGroupId(to.userId)];
54
+ return [...new Set(to.userIds)].map(assertGroupId);
55
+ }
56
+ function assertGroupId(id) {
57
+ if (!isTopicSafeId(id))
58
+ throw new Error(`Invalid realtime id: ${JSON.stringify(id)}`);
59
+ return id;
60
+ }
61
+ export {
62
+ createRealtimePublisher
63
+ };
@@ -0,0 +1,30 @@
1
+ // packages/realtime-server/src/env.ts
2
+ import { isTopicSafeId } from "@beesolve/realtime-core";
3
+ import * as v from "valibot";
4
+ function parseAuthorizerEnv(env) {
5
+ const seconds = v.pipe(v.string(), v.transform(Number), v.number(), v.integer(), v.minValue(1));
6
+ const schema = v.object({
7
+ BEESOLVE_REALTIME_SCOPE: v.pipe(v.string(), v.check(isTopicSafeId, "Invalid scope")),
8
+ BEESOLVE_REALTIME_REFRESH_SECONDS: seconds,
9
+ BEESOLVE_REALTIME_MAX_CONNECTION_SECONDS: seconds
10
+ });
11
+ const parsed = v.parse(schema, env);
12
+ return {
13
+ scope: parsed.BEESOLVE_REALTIME_SCOPE,
14
+ refreshSeconds: parsed.BEESOLVE_REALTIME_REFRESH_SECONDS,
15
+ maxConnectionSeconds: parsed.BEESOLVE_REALTIME_MAX_CONNECTION_SECONDS
16
+ };
17
+ }
18
+ function parsePublisherEnv(env) {
19
+ const schema = v.object({
20
+ BEESOLVE_REALTIME_ENDPOINT: v.optional(v.pipe(v.string(), v.minLength(1))),
21
+ BEESOLVE_REALTIME_SCOPE: v.optional(v.pipe(v.string(), v.check(isTopicSafeId, "Invalid scope")))
22
+ });
23
+ const parsed = v.parse(schema, env);
24
+ return {
25
+ endpoint: parsed.BEESOLVE_REALTIME_ENDPOINT,
26
+ scope: parsed.BEESOLVE_REALTIME_SCOPE
27
+ };
28
+ }
29
+
30
+ export { parseAuthorizerEnv, parsePublisherEnv };
@@ -0,0 +1,70 @@
1
+ # How to: Write a Custom Authorizer
2
+
3
+ `createRealtimeAuthorizerHandler` owns everything IoT-specific: policy building (chunked into up to 10 documents of 2048 characters), id validation and clamping of refresh and disconnect times. Your function only answers who the caller is, which extra groups they get and until when.
4
+
5
+ ## Steps
6
+
7
+ ### 1. Write the handler
8
+
9
+ This example verifies a JWT from a cookie with the `jose` package.
10
+
11
+ ```ts
12
+ import { createRealtimeAuthorizerHandler } from "@beesolve/realtime-server/authorizer";
13
+ import { jwtVerify } from "jose";
14
+
15
+ const secret = new TextEncoder().encode(process.env.JWT_SECRET);
16
+
17
+ export const handler = createRealtimeAuthorizerHandler(async ({ headers }) => {
18
+ const token = readCookie(headers.get("cookie"), "token");
19
+ if (token == null) return { type: "deny", reason: "no token" };
20
+ try {
21
+ const { payload } = await jwtVerify(token, secret);
22
+ if (payload.sub == null) return { type: "deny", reason: "no subject" };
23
+ return {
24
+ type: "allow",
25
+ userId: payload.sub,
26
+ groups: Array.isArray(payload.teams) ? payload.teams.map(String) : [],
27
+ expiresAt: payload.exp == null ? undefined : new Date(payload.exp * 1000),
28
+ };
29
+ } catch {
30
+ return { type: "deny", reason: "invalid token" };
31
+ }
32
+ });
33
+
34
+ function readCookie(header: string | null, name: string): string | undefined {
35
+ return header
36
+ ?.split(";")
37
+ .map((part) => part.trim().split("="))
38
+ .find(([key]) => key === name)?.[1];
39
+ }
40
+ ```
41
+
42
+ The request has `headers` (a `Headers`), `query` (a `URLSearchParams`) and `clientId`. The cookie arrives in the `cookie` header because the construct forwards the cookies you list.
43
+
44
+ ### 2. Wire it to the construct
45
+
46
+ ```ts
47
+ const authorizerFunction = new NodejsFunction(this, "RealtimeAuthorizer", {
48
+ entry: "authorizer.ts",
49
+ environment: { JWT_SECRET: secret },
50
+ });
51
+
52
+ const realtime = new Realtime(this, "Realtime", {
53
+ scope: "myapp-dev",
54
+ authorizer: { handler: authorizerFunction, cookies: ["token"] },
55
+ });
56
+ ```
57
+
58
+ ## Behavior
59
+
60
+ - `userId` and every group must match `[A-Za-z0-9_-]{1,128}`. Otherwise the connection is denied.
61
+ - The connection receives the user's own group (`userId`), the broadcast group and your extra groups.
62
+ - The connection closes at the earlier of `expiresAt` and the construct's `maxConnectionDuration`, clamped to 5 minutes to 24 hours.
63
+ - A thrown error, a deny result, or too many groups for the policy limit denies the connection. Denies are logged as `realtime-authorizer-deny`.
64
+ - The handler reads `BEESOLVE_REALTIME_SCOPE`, `BEESOLVE_REALTIME_REFRESH_SECONDS` and `BEESOLVE_REALTIME_MAX_CONNECTION_SECONDS` when it is created. `Realtime` sets them.
65
+ - Do not rotate or write sessions here. IoT refreshes re-run the authorizer with the original handshake headers and cannot deliver `Set-Cookie`.
66
+
67
+ ## See Also
68
+
69
+ - [Getting Started](./getting-started.md)
70
+ - [Limits](./limits.md)
@@ -0,0 +1,16 @@
1
+ # How to: Understand Delivery Semantics on the Server
2
+
3
+ Delivery is best effort. Sessions are clean (`cleanSession: true`), there is no offline queue, and a message sent while a browser is disconnected is lost. The pattern is "notify, then refetch or apply". The client reports `connected` after every reconnect so apps can refetch state. See the [client guide](https://github.com/BeeSolve/packages/tree/main/packages/realtime-client/docs/how-to/delivery-semantics.md).
4
+
5
+ ## Server side facts
6
+
7
+ - `publish()` sends with QoS 1 and resolves after the IoT broker accepted the message. It does not confirm delivery to a browser.
8
+ - With several targets the other topics are still sent when one fails. The call then throws an `AggregateError` that names the failed topics.
9
+ - **Revocation latency equals `refreshAfter`.** IoT refreshes lazily, on the first message after the interval, using the original handshake headers. With the default of 1 hour a signed-out user can receive messages for up to 1 hour. Lower `refreshAfter` (down to 5 minutes) when that matters. The cost is one authorizer run per active connection per interval.
10
+ - **Session rotation causes a reconnect about once an hour with auth-service.** It rotates the session id every `refreshInterval` and lets the old id expire after about 30 seconds. An IoT refresh after a rotation presents a dead id, IoT closes the connection, and the client reconnects with the new cookie.
11
+ - The authorizer for auth-service is read-only (`SessionAuthorizer.verify`), because refreshes cannot deliver `Set-Cookie`.
12
+
13
+ ## See Also
14
+
15
+ - [Getting Started](./getting-started.md)
16
+ - [Limits](./limits.md)
@@ -0,0 +1,83 @@
1
+ # How to: Set Up Realtime Updates
2
+
3
+ ## Prerequisites
4
+
5
+ - A CloudFront `Distribution` that serves your app
6
+ - An authorizer: auth-service (below) or your own (see the custom authorizer guide)
7
+ - Channels defined with `@beesolve/realtime-core`
8
+
9
+ ## Steps
10
+
11
+ ### 1. Install
12
+
13
+ ```sh
14
+ bun add @beesolve/realtime-server @beesolve/realtime-core
15
+ bun add @beesolve/realtime-client @beesolve/realtime-core
16
+ ```
17
+
18
+ The first line is for the backend, the second for the browser app.
19
+
20
+ ### 2. Define channels
21
+
22
+ ```ts
23
+ import { defineChannel } from "@beesolve/realtime-core";
24
+ import * as v from "valibot";
25
+
26
+ export const orderPaid = defineChannel({
27
+ name: "orders/paid",
28
+ schema: v.object({ orderId: v.string() }),
29
+ });
30
+ ```
31
+
32
+ ### 3. Add the construct
33
+
34
+ ```ts
35
+ import { Realtime } from "@beesolve/realtime-server/cdk";
36
+
37
+ const realtime = new Realtime(this, "Realtime", {
38
+ scope: "myapp-dev",
39
+ authorizer: auth.createRealtimeAuthorizer(this, "RealtimeAuthorizer"),
40
+ });
41
+ realtime.addToDistribution(distribution);
42
+ realtime.grantPublish(appFunction);
43
+ ```
44
+
45
+ `auth.createRealtimeAuthorizer` comes from `@beesolve/auth-service` (see its [realtime guide](https://github.com/BeeSolve/packages/tree/main/packages/service-auth/docs/how-to/realtime.md)). It returns `{ handler, cookies: ["__Host-SID"] }`. `grantPublish` gives the Lambda `iot:Publish` on the scope and sets `BEESOLVE_REALTIME_ENDPOINT` and `BEESOLVE_REALTIME_SCOPE`.
46
+
47
+ `addToDistribution` takes a CloudFront `Distribution` and adds a `/mqtt` behavior with a CloudFront Function that sets the authorizer name query string, plus an origin request policy that forwards only the listed cookies, the four `Sec-WebSocket-*` headers and that query string.
48
+
49
+ ### 4. Publish
50
+
51
+ ```ts
52
+ import { createRealtimePublisher } from "@beesolve/realtime-server/publish";
53
+
54
+ const publisher = createRealtimePublisher();
55
+
56
+ await publisher.publish({ channel: orderPaid, to: { userId }, payload: { orderId } });
57
+ await publisher.publish({ channel: orderPaid, to: { broadcast: true }, payload: { orderId } });
58
+ ```
59
+
60
+ Targets: `{ userId }`, `{ userIds }`, `{ group }`, `{ broadcast: true }`. Extra groups come from the authorizer result.
61
+
62
+ ### 5. Subscribe in the browser
63
+
64
+ ```ts
65
+ import { createRealtimeClient } from "@beesolve/realtime-client";
66
+
67
+ const realtime = createRealtimeClient({ scope: "myapp-dev" });
68
+ realtime.subscribe(orderPaid, ({ orderId }) => console.log(orderId));
69
+ ```
70
+
71
+ ## Common Pitfalls
72
+
73
+ - The authorizer `handler` must be a `lambda.Function`, not an `IFunction` import. The construct adds environment variables to it.
74
+ - `addToDistribution` can be called once per `Realtime`.
75
+ - Use one scope per app and stage. The client `scope` must match.
76
+ - A new account needs enough Lambda concurrency and, with auth-service, a bootstrapped us-east-1 (Lambda@Edge).
77
+ - First deploy: the CloudFront URL does not exist yet. Deploy, read the URL, then configure anything that needs it.
78
+
79
+ ## See Also
80
+
81
+ - [Custom Authorizer](./custom-authorizer.md)
82
+ - [Delivery Semantics](./delivery-semantics.md)
83
+ - [Limits](./limits.md)
@@ -0,0 +1,18 @@
1
+ # How to: Stay Within the Limits
2
+
3
+ | Limit | Value | Notes |
4
+ | ------------------------------ | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
5
+ | Channels per browser tab | 50 | AWS IoT allows 50 subscriptions per connection. The client uses one per channel. |
6
+ | Payload size | 128 KB | `publish()` throws above it. Messages are metered in 5 KB increments. |
7
+ | Topic length | under 256 bytes | `<scope>/<group>/<channel>`. |
8
+ | Topic levels | 8 | Scope and group take 2, a channel takes 1 to 6. |
9
+ | Ids (scope, user, group) | `[A-Za-z0-9_-]{1,128}` | Validated by the authorizer handler and publisher. |
10
+ | Groups per connection | policy size bound | Policies are chunked into up to 10 documents of 2048 characters. About 150 short groups fit and 300 do not. The authorizer denies when they do not fit. |
11
+ | Refresh and disconnect times | 5 minutes to 24 hours | `refreshAfter` and `maxConnectionDuration` are clamped. |
12
+ | Custom authorizers per account | 32 active | Use one `Realtime` per app and stage. |
13
+ | IoT logging | one configuration per account and region | See the logging guide. |
14
+
15
+ ## See Also
16
+
17
+ - [Getting Started](./getting-started.md)
18
+ - [Logging](./logging.md)
@@ -0,0 +1,64 @@
1
+ # How to: Enable IoT Logging
2
+
3
+ IoT logging is opt-in. `Realtime` does not turn it on.
4
+
5
+ ## Steps
6
+
7
+ ```ts
8
+ import { RealtimeLogging } from "@beesolve/realtime-server/cdk";
9
+ import { RetentionDays } from "aws-cdk-lib/aws-logs";
10
+
11
+ new RealtimeLogging(this, "RealtimeLogging", {
12
+ level: "ERROR",
13
+ retention: RetentionDays.ONE_MONTH,
14
+ });
15
+ ```
16
+
17
+ | Prop | Default | Description |
18
+ | ---------------- | --------- | ------------------------------------------------------------------------------ |
19
+ | `level` | `"ERROR"` | Default level: `ERROR`, `WARN`, `INFO` or `DEBUG`. |
20
+ | `retention` | two weeks | Retention of the `AWSIotLogsV2` log group. |
21
+ | `createLogGroup` | `true` | Creates the log group first so it has retention. IoT would create one without. |
22
+ | `eventOverrides` | none | `{ eventType, level }` entries. `level` may also be `DISABLED`. |
23
+
24
+ ## Pitfalls
25
+
26
+ - **Account and region singleton.** Create at most one `RealtimeLogging` per account and region. Deleting the stack disables IoT logging for the whole account and region.
27
+ - AWS defaults `Connection.AuthNError` and `Ping` to `DISABLED`. IoT merges overrides per event and never removes these defaults, so passing an empty list does not clear them.
28
+ - Rejected handshakes are still logged as `Connect` failures with `AUTHORIZATION_FAILURE`.
29
+ - INFO logs every publish in and out (about 400 bytes per event) and can cost more than the messaging itself. It adds roughly 30% in the cost example in the README.
30
+ - Use `createLogGroup: false` only if you already manage the `AWSIotLogsV2` group.
31
+
32
+ ## Troubleshooting: "AWSIotLogsV2 already exists"
33
+
34
+ The deploy fails with `Resource of type 'AWS::Logs::LogGroup' with identifier 'AWSIotLogsV2' already exists`. IoT logging was enabled in this account and region before, outside this stack, so IoT created the log group itself. That group usually has no retention.
35
+
36
+ Check the existing group and the current logging options:
37
+
38
+ ```sh
39
+ aws logs describe-log-groups --log-group-name-prefix AWSIotLogsV2 \
40
+ --query 'logGroups[].{name:logGroupName,retentionDays:retentionInDays,bytes:storedBytes}'
41
+ aws iot get-v2-logging-options
42
+ ```
43
+
44
+ Then pick one option.
45
+
46
+ **Option A: let the stack own the group.** You lose the existing IoT logs. Export them first if you need them. Delete the group and deploy again with the default `createLogGroup: true`:
47
+
48
+ ```sh
49
+ aws logs delete-log-group --log-group-name AWSIotLogsV2
50
+ ```
51
+
52
+ **Option B: keep the existing group.** Set `createLogGroup: false` and give the group a retention yourself, because the stack no longer manages it:
53
+
54
+ ```sh
55
+ aws logs put-retention-policy --log-group-name AWSIotLogsV2 --retention-in-days 14
56
+ ```
57
+
58
+ Add `--profile <profile>` and `--region <region>` to every command if you don't use the defaults. Run the commands in the region of the `Realtime` stack.
59
+
60
+ If `get-v2-logging-options` shows a `roleArn` that points to a deleted role, `RealtimeLogging` replaces it on deploy. You don't need to clean it up first.
61
+
62
+ ## See Also
63
+
64
+ - [Getting Started](./getting-started.md)
package/package.json CHANGED
@@ -1,14 +1,56 @@
1
1
  {
2
2
  "name": "@beesolve/realtime-server",
3
- "version": "0.0.0",
4
- "description": "Placeholder package to reserve the npm name and configure OIDC Trusted Publisher.",
3
+ "version": "0.1.0",
5
4
  "license": "MIT",
6
5
  "repository": {
7
6
  "type": "git",
8
- "url": "git+https://github.com/BeeSolve/packages.git",
9
- "directory": "packages/realtime-server"
7
+ "url": "git+https://github.com/BeeSolve/packages.git"
10
8
  },
11
- "publishConfig": {
12
- "access": "public"
9
+ "files": [
10
+ "dist",
11
+ "docs/how-to",
12
+ "DOCS.md"
13
+ ],
14
+ "type": "module",
15
+ "exports": {
16
+ "./cdk": {
17
+ "import": {
18
+ "types": "./dist/cdk.d.ts",
19
+ "default": "./dist/cdk.js"
20
+ }
21
+ },
22
+ "./authorizer": {
23
+ "import": {
24
+ "types": "./dist/authorizer.d.ts",
25
+ "default": "./dist/authorizer.js"
26
+ }
27
+ },
28
+ "./publish": {
29
+ "import": {
30
+ "types": "./dist/publish.d.ts",
31
+ "default": "./dist/publish.js"
32
+ }
33
+ },
34
+ "./package.json": "./package.json"
35
+ },
36
+ "scripts": {
37
+ "type-check": "tsc --noEmit"
38
+ },
39
+ "dependencies": {
40
+ "@beesolve/cdk-constructs": "^1.1.0",
41
+ "@beesolve/realtime-core": "^0.1.0",
42
+ "@standard-schema/spec": "^1.1.0",
43
+ "valibot": "^1.5.0"
44
+ },
45
+ "devDependencies": {
46
+ "@aws-sdk/client-iot-data-plane": "^3.1178.0",
47
+ "@types/aws-lambda": "^8.10.164",
48
+ "aws-cdk-lib": "^2.278.0",
49
+ "constructs": "^10.8.1"
50
+ },
51
+ "peerDependencies": {
52
+ "@aws-sdk/client-iot-data-plane": "^3.1178.0",
53
+ "aws-cdk-lib": "^2.278.0",
54
+ "constructs": "^10.8.1"
13
55
  }
14
56
  }