@openreachtech/hora-skills-ort-renchan 0.4.0 → 0.5.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.
|
@@ -3,10 +3,9 @@ name: hor-graphql-server-engine
|
|
|
3
3
|
description: >
|
|
4
4
|
Implement and wire a GraphQL server engine, the per-endpoint *GraphqlServerEngine class under
|
|
5
5
|
server/graphql/ that declares one endpoint's routing, Share and Context DI, auth filter,
|
|
6
|
-
middleware, scalars and
|
|
7
|
-
reads env. Use whenever the user
|
|
8
|
-
|
|
9
|
-
PubSub.
|
|
6
|
+
middleware, scalars, error codes and WebSocket server, and decide what the engine and its Share
|
|
7
|
+
may hold and who reads env. Use whenever the user adds a GraphQL endpoint, pairs a stub engine,
|
|
8
|
+
changes its auth policy or credential route, enables Redis PubSub, or limits its WebSocket server.
|
|
10
9
|
---
|
|
11
10
|
|
|
12
11
|
# GraphQL Server Engine
|
|
@@ -14,7 +13,8 @@ description: >
|
|
|
14
13
|
A skill for the **`*GraphqlServerEngine` classes under `server/graphql/`**. An engine is the one
|
|
15
14
|
object that **wires a single GraphQL endpoint**: its URL and port, which schema and resolver
|
|
16
15
|
directories to load, the Share / Context dependency-injection classes, the authentication filter,
|
|
17
|
-
the Express middleware, the custom scalars,
|
|
16
|
+
the Express middleware, the custom scalars, the error-code hash, and the WebSocket server's hooks and
|
|
17
|
+
switches. `server/index.js` then boots
|
|
18
18
|
**one HTTP server per engine** through `GraphqlServerBuilder`.
|
|
19
19
|
|
|
20
20
|
The engine sits *above* the pieces other skills build: resolvers (`hor-resolver-validator`
|
|
@@ -39,6 +39,7 @@ one of these settings — nothing more:
|
|
|
39
39
|
| Custom scalars | `collectScalars()` | [§6](#6-middleware-scalars-error-codes) |
|
|
40
40
|
| Auth policy — the **no-auth (public) operations** + the filter | `schemasToSkipFiltering` + `generateFilterHandler()` | [§4](#4-authentication-schemastoskipfiltering--generatefilterhandler) |
|
|
41
41
|
| Shared error codes | `standardErrorCodeHash` | [§6](#6-middleware-scalars-error-codes) |
|
|
42
|
+
| WebSocket server (`graphql-ws` hooks, skip switch, `ConnectionInit` timeout) | `composeServerHookHash()` + `config.graphqlServer` | [§9](#9-the-websocket-server-composeserverhookhash--graphqlserver) |
|
|
42
43
|
|
|
43
44
|
**App-common settings are not repeated per engine** — they are lifted into an **app base class**
|
|
44
45
|
(`BaseAppGraphqlServerEngine`) that every engine extends ([§1](#1-two-base-classes-put-app-common-settings-in-an-app-base-and-extend-it)).
|
|
@@ -132,6 +133,7 @@ export default class PartnerGraphqlServerEngine extends BaseAppGraphqlServerEngi
|
|
|
132
133
|
| `actualResolversPath` | Directory of the real resolvers (`.../resolvers/<role>/actual/`), or `null`. |
|
|
133
134
|
| `stubResolversPath` | Directory of stub resolvers (`.../resolvers/<role>/stub/`), or `null`. |
|
|
134
135
|
| `postWorkersPath` | Directory of post-workers, or `null` when unused ([§7](#7-post-resolve-hooks-defineonresolved--postworkerspath)). |
|
|
136
|
+
| `graphqlServer?` | Settings of the WebSocket server mounted on the endpoint: `skipsWebSocket` and `connectionInitWaitTimeout` ([§9](#9-the-websocket-server-composeserverhookhash--graphqlserver)). |
|
|
135
137
|
| `redisOptions?` | Redis connection for subscription PubSub, read by the subscription broker. The engine leaves it out; the Share adds it from `env` when it creates the broker ([§3](#3-share-and-context--the-di-the-engine-hands-to-every-resolver)). `null` → in-process `LocalPubSub` ([§5](#5-stub-vs-actual-engines-and-subscriptions-redis-vs-local)). |
|
|
136
138
|
|
|
137
139
|
```js
|
|
@@ -672,6 +674,169 @@ An endpoint → port layout looks like this (roles, paths, and ports are illustr
|
|
|
672
674
|
as a REST server).
|
|
673
675
|
- Pair the actual engine with its stub engine here too (both get their own `createAsync` + `listen`).
|
|
674
676
|
|
|
677
|
+
## 9. The WebSocket server: `composeServerHookHash()` + `graphqlServer`
|
|
678
|
+
|
|
679
|
+
`GraphqlServerBuilder` mounts a `graphql-ws` server on the endpoint's `graphqlEndpoint` path, next to
|
|
680
|
+
the HTTP handler. The engine shapes it through two members, from `@openreachtech/renchan` `2.12.0`.
|
|
681
|
+
A WebSocket connection never passes through the Express middleware of
|
|
682
|
+
[§6](#6-middleware-scalars-error-codes), so a rule that lives there (a sign-in rate limit, a CORS
|
|
683
|
+
check) does not see an operation that arrives over the socket.
|
|
684
|
+
|
|
685
|
+
| Member | Kind | What it decides |
|
|
686
|
+
| --- | --- | --- |
|
|
687
|
+
| `composeServerHookHash()` | instance method | The `graphql-ws` server hooks (`onConnect`, `onSubscribe`, `onClose`, ...). Default `{}`. Type `GraphqlType.WebSocketServerHookHash`. |
|
|
688
|
+
| `config.graphqlServer.skipsWebSocket` | boolean | `true` leaves the WebSocket server unmounted. Default `false`. |
|
|
689
|
+
| `config.graphqlServer.connectionInitWaitTimeout` | number (ms) | How long the server waits for `ConnectionInit` after a connection opens. A positive finite number only; anything else (omitted, `null`, `0`, `Infinity`, `NaN`, a string) leaves the `graphql-ws` default of 3000. |
|
|
690
|
+
|
|
691
|
+
- **A switch goes in `config`, and a hook never overrides what the builder wires.** The builder drops
|
|
692
|
+
these keys from whatever `composeServerHookHash()` returns: `execute`, `subscribe`, `context`,
|
|
693
|
+
`schema`, `roots`, `validate`, `connectionInitWaitTimeout`, `jsonMessageReviver` and
|
|
694
|
+
`jsonMessageReplacer`. The type omits the same keys, and the builder ignores one that slips
|
|
695
|
+
through. Set the wait through `config`, never through the hash.
|
|
696
|
+
- **`0` and `Infinity` do not turn the wait off.** `graphql-ws` itself treats them as "do not wait",
|
|
697
|
+
but the builder resolves them to its default, so an endpoint always waits for `ConnectionInit`.
|
|
698
|
+
- **Skip the server on an endpoint that serves no subscription.** An endpoint whose schema has no
|
|
699
|
+
`Subscription` type, such as a role that only queries and mutates, mounts a WebSocket server
|
|
700
|
+
nobody needs, and an open door is attack surface. `skipsWebSocket: true` is the switch; do not
|
|
701
|
+
emulate it with a hook that refuses everything.
|
|
702
|
+
- **`composeServerHookHash()` is a method, so it may build the hash.** The getter rule of
|
|
703
|
+
[§3](#what-the-engine-the-share-and-env-may-each-hold) holds: a getter calls no method. The method
|
|
704
|
+
returns hook functions that decide allow or deny and nothing else, like `generateFilterHandler()`
|
|
705
|
+
([§4](#4-authentication-schemastoskipfiltering--generatefilterhandler)). Anything that needs `env`
|
|
706
|
+
reads it through `this.share.env`, because only the Share imports `env`.
|
|
707
|
+
- **Refuse an operation by returning `GraphQLError`s from `onSubscribe`.** Return `void` to let the
|
|
708
|
+
operation go on. Return an array of at least one `GraphQLError` (from `graphql`) to refuse it:
|
|
709
|
+
`graphql-ws` sends the client an error message for that operation and the socket stays open.
|
|
710
|
+
An error from `this.errorHash` does not qualify, because it extends `Error` and is not a
|
|
711
|
+
`GraphQLError`.
|
|
712
|
+
- **Never return `ExecutionArgs` from `onSubscribe`.** It skips the builder's validation, so the
|
|
713
|
+
endpoint's own validation rules stop applying to that operation.
|
|
714
|
+
- **Throwing from `onSubscribe` closes the whole socket.** `parse()` throws on a syntax error, so the
|
|
715
|
+
example below ends the connection on a malformed query, as `graphql-ws` does when no hook is set.
|
|
716
|
+
|
|
717
|
+
```js
|
|
718
|
+
// Good: a WebSocket carries subscriptions only; a query or a mutation must go through HTTP
|
|
719
|
+
import {
|
|
720
|
+
GraphQLError,
|
|
721
|
+
getOperationAST,
|
|
722
|
+
parse,
|
|
723
|
+
} from 'graphql'
|
|
724
|
+
|
|
725
|
+
/** @override */
|
|
726
|
+
composeServerHookHash () {
|
|
727
|
+
return {
|
|
728
|
+
onSubscribe: (context, message) => {
|
|
729
|
+
const operationAst = getOperationAST(
|
|
730
|
+
parse(message.payload.query),
|
|
731
|
+
message.payload.operationName
|
|
732
|
+
)
|
|
733
|
+
|
|
734
|
+
if (operationAst?.operation === 'subscription') {
|
|
735
|
+
return undefined
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
return [
|
|
739
|
+
new GraphQLError('Only a subscription is accepted over WebSocket.'),
|
|
740
|
+
]
|
|
741
|
+
},
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
```
|
|
745
|
+
|
|
746
|
+
An operation the hook refuses never reaches a resolver, so a sign-in mutation sent over the socket
|
|
747
|
+
cannot dodge the sign-in rate limit that the Express middleware applies over HTTP. The check fails
|
|
748
|
+
closed: anything other than a subscription, including an operation the AST cannot identify
|
|
749
|
+
(`operationAst` is `null`), is refused.
|
|
750
|
+
|
|
751
|
+
### Check the `Origin` of a WebSocket connection in `onConnect`
|
|
752
|
+
|
|
753
|
+
The CORS middleware of [§3](#what-the-engine-the-share-and-env-may-each-hold) never sees the
|
|
754
|
+
WebSocket handshake either, so a page on any origin can open a socket to the endpoint. `onConnect`
|
|
755
|
+
runs when the client sends `ConnectionInit`: `graphql-ws` allows the connection when it returns
|
|
756
|
+
`true` (or nothing), and closes the socket with `4403: Forbidden` when it returns `false`. With the
|
|
757
|
+
`ws` server, `context.extra.request` is the handshake `IncomingMessage`, so the origin is
|
|
758
|
+
`context.extra.request.headers.origin`.
|
|
759
|
+
|
|
760
|
+
The allowed origins already live in the endpoint's `CorsExpressMiddleware` derived class, which
|
|
761
|
+
reads its env key through `this.share.env`. Give that class the one predicate the hook needs, and
|
|
762
|
+
create the class in the engine with `Ctor.create({ engine: this })`, as
|
|
763
|
+
`composeExpressMiddleware()` does. The engine then imports no `env`, parses nothing and keeps one
|
|
764
|
+
list of origins for HTTP and WebSocket.
|
|
765
|
+
|
|
766
|
+
```js
|
|
767
|
+
// Good: the middleware class owns the origin list, so the hook only asks it
|
|
768
|
+
// server/middleware/CorsExpressMiddleware.js
|
|
769
|
+
allowsOrigin ({
|
|
770
|
+
origin,
|
|
771
|
+
}) {
|
|
772
|
+
return this.createAllowedCorsOriginCollection()
|
|
773
|
+
.extractOrigins()
|
|
774
|
+
.includes(origin)
|
|
775
|
+
}
|
|
776
|
+
```
|
|
777
|
+
|
|
778
|
+
```js
|
|
779
|
+
// Good: the engine composes the hook; a missing or foreign Origin is refused with 4403
|
|
780
|
+
import AdminCorsExpressMiddleware from '../middleware/AdminCorsExpressMiddleware.js'
|
|
781
|
+
|
|
782
|
+
/** @override */
|
|
783
|
+
composeServerHookHash () {
|
|
784
|
+
const corsExpressMiddleware = AdminCorsExpressMiddleware.create({
|
|
785
|
+
engine: this,
|
|
786
|
+
})
|
|
787
|
+
|
|
788
|
+
return {
|
|
789
|
+
onConnect: context => corsExpressMiddleware.allowsOrigin({
|
|
790
|
+
origin: context.extra.request.headers.origin,
|
|
791
|
+
}),
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
```
|
|
795
|
+
|
|
796
|
+
- **A browser always sends `Origin` on a WebSocket handshake; a script or a server client sends none.**
|
|
797
|
+
The hook above refuses a connection with no `Origin`. An endpoint that serves such a client
|
|
798
|
+
decides that case on purpose, never by loosening the list.
|
|
799
|
+
- **`onConnect` and `onSubscribe` live in the same hash.** Return both from one
|
|
800
|
+
`composeServerHookHash()`.
|
|
801
|
+
|
|
802
|
+
```js
|
|
803
|
+
// Good: a switch is a config value
|
|
804
|
+
/** @override */
|
|
805
|
+
static get config () {
|
|
806
|
+
return {
|
|
807
|
+
graphqlEndpoint: '/graphql-admin',
|
|
808
|
+
// ...
|
|
809
|
+
graphqlServer: {
|
|
810
|
+
skipsWebSocket: false,
|
|
811
|
+
connectionInitWaitTimeout: 5000,
|
|
812
|
+
},
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
```
|
|
816
|
+
|
|
817
|
+
```js
|
|
818
|
+
// Bad: the wait is a config value, so the builder drops it from the hash
|
|
819
|
+
/** @override */
|
|
820
|
+
composeServerHookHash () {
|
|
821
|
+
return {
|
|
822
|
+
connectionInitWaitTimeout: 5000,
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
```
|
|
826
|
+
|
|
827
|
+
```js
|
|
828
|
+
// Bad: ExecutionArgs from onSubscribe skips the builder's validation
|
|
829
|
+
/** @override */
|
|
830
|
+
composeServerHookHash () {
|
|
831
|
+
return {
|
|
832
|
+
onSubscribe: (context, message) => ({
|
|
833
|
+
schema,
|
|
834
|
+
document: parse(message.payload.query),
|
|
835
|
+
}),
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
```
|
|
839
|
+
|
|
675
840
|
## Finishing checklist
|
|
676
841
|
|
|
677
842
|
- [ ] One engine per endpoint, extending the **app base** ([§1](#1-two-base-classes-put-app-common-settings-in-an-app-base-and-extend-it)); a member moves to the app base only when it is always the same for every endpoint, and `collectMiddleware()` stays in each engine.
|
|
@@ -686,3 +851,5 @@ An endpoint → port layout looks like this (roles, paths, and ports are illustr
|
|
|
686
851
|
- [ ] Redis PubSub enabled on endpoints whose subscriptions are published by **another process** ([§5](#5-stub-vs-actual-engines-and-subscriptions-redis-vs-local)).
|
|
687
852
|
- [ ] `postWorkersPath` set when the endpoint needs post-workers (`null` disables them) ([§7](#7-post-resolve-hooks-defineonresolved--postworkerspath)).
|
|
688
853
|
- [ ] Engine **registered in `server/index.js`** with a unique port ([§8](#8-wiring-into-serverindexjs)).
|
|
854
|
+
- [ ] An endpoint's `onConnect` refuses an `Origin` outside the list its `CorsExpressMiddleware` derived class reads, and the engine imports no `env` for it ([§9](#9-the-websocket-server-composeserverhookhash--graphqlserver)).
|
|
855
|
+
- [ ] An endpoint that serves no subscription sets `config.graphqlServer.skipsWebSocket: true`; one that does refuses every non-subscription operation in `composeServerHookHash()`'s `onSubscribe`, returns `GraphQLError`s (never `ExecutionArgs`), and keeps `connectionInitWaitTimeout` in `config` ([§9](#9-the-websocket-server-composeserverhookhash--graphqlserver)).
|
package/docs/skills.ja.md
CHANGED
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
| スキル | 概要 |
|
|
23
23
|
| :-- | :-- |
|
|
24
24
|
| `hor-graphql-schema` | renchan サーバの GraphQL SDL(`.graphql`)を書きます。オーディエンス別スキーマ、ドメイン別の番号付きファイル、カスタムスカラー、命名・null 許容・enum・ページネーションの規約。 |
|
|
25
|
-
| `hor-graphql-server-engine` | エンドポイントごとの `*GraphqlServerEngine` を実装・起動します。URL、スキーマパス、リゾルバディレクトリ、Share/Context の DI
|
|
25
|
+
| `hor-graphql-server-engine` | エンドポイントごとの `*GraphqlServerEngine` を実装・起動します。URL、スキーマパス、リゾルバディレクトリ、Share/Context の DI、認証フィルタ、ミドルウェア、スカラー、エラーコード、WebSocket サーバーの制限。 |
|
|
26
26
|
| `hor-query-resolver` | `BaseQueryResolver` を継承した GraphQL Query リゾルバを書きます。ページネーション、関連の include、ドメインエラーの throw、actual と stub のペア。 |
|
|
27
27
|
| `hor-mutation-resolver` | `BaseMutationResolver` を継承した GraphQL Mutation リゾルバを実装します。状態を変更する操作と、それが動く単一トランザクション。 |
|
|
28
28
|
| `hor-subscription-resolver` | GraphQL subscription リゾルバを実装します。操作の宣言、購読者ごとのチャンネルのスコープ、購読可否のゲート、イベントを push する publish 側の配線。 |
|
package/docs/skills.md
CHANGED
|
@@ -22,7 +22,7 @@ Each skill lives at `kit/skills/<name>/`, directly under the skills directory, a
|
|
|
22
22
|
| Skill | Summary |
|
|
23
23
|
| :-- | :-- |
|
|
24
24
|
| `hor-graphql-schema` | Author GraphQL SDL files for a renchan server — per-audience schemas, numbered per-domain files, custom scalars, and naming, nullability, enum and pagination conventions. |
|
|
25
|
-
| `hor-graphql-server-engine` | Implement a per-endpoint `*GraphqlServerEngine`: its URL, schema path, resolver directories, Share/Context DI, auth filter, middleware, scalars and
|
|
25
|
+
| `hor-graphql-server-engine` | Implement a per-endpoint `*GraphqlServerEngine`: its URL, schema path, resolver directories, Share/Context DI, auth filter, middleware, scalars, error codes and WebSocket server limits. |
|
|
26
26
|
| `hor-query-resolver` | Write GraphQL Query resolvers extending `BaseQueryResolver` — pagination, association includes, domain-error throwing, and the actual-vs-stub pair. |
|
|
27
27
|
| `hor-mutation-resolver` | Implement GraphQL Mutation resolvers extending `BaseMutationResolver` — state-changing operations and the single transaction each runs in. |
|
|
28
28
|
| `hor-subscription-resolver` | Implement a GraphQL subscription resolver — declare the operation, scope its channel per subscriber, gate who may subscribe, and wire the publish side. |
|