@plingjs/surface-gateway 0.0.0-stage → 0.1.0-alpha.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +177 -2
- package/bin/surface-gateway.mjs +19 -0
- package/cli.mjs +132 -0
- package/config.example.json +33 -0
- package/config.mjs +214 -0
- package/errors.mjs +15 -0
- package/gateway.mjs +935 -0
- package/index.d.ts +273 -0
- package/index.mjs +7 -0
- package/mcp.mjs +145 -0
- package/package.json +35 -4
- package/server.mjs +462 -0
- package/version.mjs +1 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/NOTICE
ADDED
package/README.md
CHANGED
|
@@ -1,3 +1,178 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @plingjs/surface-gateway
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Reference Node.js transport and control plane for a Pling Agent Surface. It
|
|
4
|
+
connects an open business page to a user-owned Agent runtime without moving page
|
|
5
|
+
execution or business permissions into the gateway.
|
|
6
|
+
|
|
7
|
+
```text
|
|
8
|
+
Agent runtime (Codex / Claude / Hermes / WorkBuddy)
|
|
9
|
+
│ MCP over HTTPS (Bearer Agent session token)
|
|
10
|
+
▼
|
|
11
|
+
surface.example.com
|
|
12
|
+
│ opaque describe / invoke envelopes over WebSocket
|
|
13
|
+
▼
|
|
14
|
+
business page (the page the user already has open)
|
|
15
|
+
│
|
|
16
|
+
▼
|
|
17
|
+
application backend + existing authorization
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
The gateway is deliberately narrow:
|
|
21
|
+
|
|
22
|
+
- it authenticates a page session created by the application backend;
|
|
23
|
+
- it binds a one-time pairing code to one Agent session;
|
|
24
|
+
- it forwards `describe`, `invoke`, approval-pending, and final responses;
|
|
25
|
+
- it enforces session TTLs, Agent scope, revocation, expiry, and audit callbacks;
|
|
26
|
+
- it never exposes DOM, `click(selector)`, script evaluation, cookies, or provider keys.
|
|
27
|
+
|
|
28
|
+
The page's Surface session remains the capability and approval authority. The
|
|
29
|
+
application backend remains the business authorization authority.
|
|
30
|
+
|
|
31
|
+
## Install
|
|
32
|
+
|
|
33
|
+
Node.js 20.12 or newer is required.
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
npm install @plingjs/surface-gateway
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Run the bundled reference server:
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
SURFACE_ADMIN_TOKEN="$(openssl rand -hex 32)" npx pling-surface-gateway
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
It listens on `http://127.0.0.1:5219` and uses the bundled
|
|
46
|
+
`config.example.json`. For a real deployment, create your own JSON config and set:
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
SURFACE_CONFIG=/etc/pling/surface.json
|
|
50
|
+
SURFACE_ADMIN_TOKEN=<server-side secret>
|
|
51
|
+
SURFACE_PUBLIC_BASE_URL=https://surface.example.com
|
|
52
|
+
SURFACE_HOST=127.0.0.1
|
|
53
|
+
SURFACE_PORT=5219
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Set `SURFACE_TRUST_PROXY=1` only when a trusted reverse proxy overwrites
|
|
57
|
+
`X-Forwarded-For`. If the gateway is directly reachable, leave it disabled or a
|
|
58
|
+
client can forge its rate-limit identity.
|
|
59
|
+
|
|
60
|
+
`SURFACE_ADMIN_TOKEN` is server-to-server only. Never put it in browser code,
|
|
61
|
+
an MCP server configuration, logs, or a public repository.
|
|
62
|
+
|
|
63
|
+
## Library API
|
|
64
|
+
|
|
65
|
+
```js
|
|
66
|
+
import {
|
|
67
|
+
createSurfaceGateway,
|
|
68
|
+
createSurfaceServer,
|
|
69
|
+
loadConfig,
|
|
70
|
+
} from "@plingjs/surface-gateway";
|
|
71
|
+
|
|
72
|
+
const config = await loadConfig("./surface.json");
|
|
73
|
+
const server = createSurfaceServer({
|
|
74
|
+
config,
|
|
75
|
+
adminToken: process.env.SURFACE_ADMIN_TOKEN,
|
|
76
|
+
publicBaseUrl: "https://surface.example.com",
|
|
77
|
+
host: "127.0.0.1",
|
|
78
|
+
port: 5219,
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
await server.start();
|
|
82
|
+
// server.gateway exposes the control-plane API for tests or custom transports.
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
The package also exports `createSurfaceGateway`, `createMcpHandler`,
|
|
86
|
+
`normalizeConfig`, `GatewayError`, and `ConfigError`. TypeScript declarations are
|
|
87
|
+
included.
|
|
88
|
+
|
|
89
|
+
## Application flow
|
|
90
|
+
|
|
91
|
+
1. The business backend verifies the signed-in user and calls
|
|
92
|
+
`POST /v1/page-sessions` with the narrow set of capability ids that page may
|
|
93
|
+
expose. It returns a short-lived page token to that page only.
|
|
94
|
+
2. The page opens `WS /surface?token=...`, sends a `pling.bridge/0.1` hello, and
|
|
95
|
+
keeps its existing Pling Surface session active.
|
|
96
|
+
3. The page calls `POST /v1/pairings` to display a one-time code. Pairing is
|
|
97
|
+
refused unless the page WebSocket is connected and the `Origin` is allowed for
|
|
98
|
+
its tenant.
|
|
99
|
+
4. The user gives the code to their Agent runtime. The runtime claims it at
|
|
100
|
+
`POST /v1/agent-sessions` and receives an Agent token and MCP URL.
|
|
101
|
+
5. The Agent configures `https://surface.example.com/mcp` with
|
|
102
|
+
`Authorization: Bearer <agent token>`. It first calls
|
|
103
|
+
`pling_surface_describe`, then `pling_surface_invoke`.
|
|
104
|
+
6. If the page requires human confirmation, the gateway returns
|
|
105
|
+
`pending_approval`. The user confirms in the business page. The Agent polls
|
|
106
|
+
`pling_surface_approval_status`; there is no approval tool and no way for the
|
|
107
|
+
Agent to approve its own request.
|
|
108
|
+
|
|
109
|
+
Pairing codes are single-use, expire after two minutes by default, and contain
|
|
110
|
+
48 random bits. Agent `invoke` calls are checked against both the page session
|
|
111
|
+
scope and the narrowed Agent scope.
|
|
112
|
+
|
|
113
|
+
## HTTP routes
|
|
114
|
+
|
|
115
|
+
| Method | Route | Authentication | Purpose |
|
|
116
|
+
| --- | --- | --- | --- |
|
|
117
|
+
| `GET` | `/health` | public | Liveness only |
|
|
118
|
+
| `GET` | `/v1/discovery/:tenantId` | public | Draft discovery metadata |
|
|
119
|
+
| `POST` | `/v1/page-sessions` | admin Bearer | Create a page session after the application has authenticated the user |
|
|
120
|
+
| `POST` | `/v1/demo/page-sessions` | configured Origin | Create a rate-limited public-demo page session |
|
|
121
|
+
| `POST` | `/v1/pairings` | page token + Origin | Create a one-time pairing code |
|
|
122
|
+
| `POST` | `/v1/agent-sessions` | pairing code | Claim a pairing and receive an Agent token |
|
|
123
|
+
| `POST` | `/v1/agent-sessions/revoke` | page token + Origin | Let the signed-in page revoke its Agent |
|
|
124
|
+
| `GET` | `/admin/sessions` | admin Bearer | Inspect live sessions |
|
|
125
|
+
| `DELETE` | `/admin/page-sessions/:id` | admin Bearer | Revoke a page and all of its Agents |
|
|
126
|
+
| `DELETE` | `/admin/agent-sessions/:id` | admin Bearer | Revoke one Agent session |
|
|
127
|
+
| `POST` | `/mcp` | Agent Bearer | JSON-RPC MCP endpoint (JSON response mode) |
|
|
128
|
+
| `WS` | `/surface?token=...` | page token + Origin | Page transport for Surface envelopes |
|
|
129
|
+
|
|
130
|
+
## MCP tools
|
|
131
|
+
|
|
132
|
+
- `pling_surface_describe` reads the paired page's current capabilities,
|
|
133
|
+
records, regions, state, and feedback.
|
|
134
|
+
- `pling_surface_invoke` invokes one capability returned by `describe`.
|
|
135
|
+
- `pling_surface_approval_status` reads the final state of an earlier invocation.
|
|
136
|
+
|
|
137
|
+
The Agent token is bound to the active HTTP request. It is not a model-visible
|
|
138
|
+
tool argument, and tool arguments cannot override it.
|
|
139
|
+
|
|
140
|
+
## Scope matching
|
|
141
|
+
|
|
142
|
+
Scopes follow `@plingjs/surface` semantics:
|
|
143
|
+
|
|
144
|
+
- `add_task` also covers `add_task:row` and `add_task@row` families;
|
|
145
|
+
- `delete@` covers concrete ids such as `delete@task`;
|
|
146
|
+
- `delete@task` does not cover the broader `delete@` family;
|
|
147
|
+
- `*` is accepted only when the page session itself allows `*`.
|
|
148
|
+
|
|
149
|
+
## Production boundary
|
|
150
|
+
|
|
151
|
+
This package is a reference implementation, not an enterprise control plane.
|
|
152
|
+
Its default stores are in memory. Before exposing it to untrusted traffic:
|
|
153
|
+
|
|
154
|
+
- terminate TLS at a reverse proxy and bind Node to loopback;
|
|
155
|
+
- use scoped, per-tenant admin credentials instead of one global control token;
|
|
156
|
+
- put shared rate limiting and abuse detection in front of pairing and MCP;
|
|
157
|
+
- persist session metadata and audit events in the application's system of record;
|
|
158
|
+
- connect approval receipts to the application's approval backend;
|
|
159
|
+
- configure one pairing per user/page, short Agent TTLs, and explicit scopes;
|
|
160
|
+
- monitor failed pairing, repeated auth failures, revocations, and approval latency.
|
|
161
|
+
|
|
162
|
+
The gateway cannot stop an Agent that already owns the browser through CDP from
|
|
163
|
+
clicking the page directly. Its security value is that declared operations have
|
|
164
|
+
identity, scope, confirmation, and audit evidence, while business authorization
|
|
165
|
+
stays in the backend.
|
|
166
|
+
|
|
167
|
+
## Test
|
|
168
|
+
|
|
169
|
+
```bash
|
|
170
|
+
pnpm --filter @plingjs/surface-gateway test
|
|
171
|
+
pnpm --filter @plingjs/surface-gateway check
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
Source and issues: [github.com/plingjs/pling](https://github.com/plingjs/pling).
|
|
175
|
+
|
|
176
|
+
## License
|
|
177
|
+
|
|
178
|
+
Apache-2.0.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { cliHelp, PACKAGE_VERSION, runSurfaceGatewayCli } from "../index.mjs";
|
|
3
|
+
|
|
4
|
+
const args = new Set(process.argv.slice(2));
|
|
5
|
+
if (args.has("--help") || args.has("-h")) {
|
|
6
|
+
process.stdout.write(cliHelp());
|
|
7
|
+
process.exit(0);
|
|
8
|
+
}
|
|
9
|
+
if (args.has("--version") || args.has("-v")) {
|
|
10
|
+
process.stdout.write(`${PACKAGE_VERSION}\n`);
|
|
11
|
+
process.exit(0);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
try {
|
|
15
|
+
await runSurfaceGatewayCli();
|
|
16
|
+
} catch (error) {
|
|
17
|
+
process.stderr.write(`[surface-gateway] ${error instanceof Error ? error.message : String(error)}\n`);
|
|
18
|
+
process.exitCode = 1;
|
|
19
|
+
}
|
package/cli.mjs
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { fileURLToPath } from "node:url";
|
|
3
|
+
import { ConfigError, loadConfig } from "./config.mjs";
|
|
4
|
+
import { createSurfaceServer } from "./server.mjs";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The same module runs from `src/` during workspace development and from the
|
|
8
|
+
* package root after publishing. Resolve both layouts instead of assuming one.
|
|
9
|
+
*/
|
|
10
|
+
export function resolveDefaultConfig(moduleUrl) {
|
|
11
|
+
const candidates = [
|
|
12
|
+
new URL("../config.example.json", moduleUrl),
|
|
13
|
+
new URL("./config.example.json", moduleUrl),
|
|
14
|
+
];
|
|
15
|
+
return fileURLToPath(candidates.find((candidate) => existsSync(candidate)) ?? candidates[0]);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const DEFAULT_CONFIG = resolveDefaultConfig(import.meta.url);
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Start the gateway from environment variables.
|
|
22
|
+
*
|
|
23
|
+
* This function is also used by the thin deployment wrapper in services/. It
|
|
24
|
+
* installs SIGINT/SIGTERM handlers by default so a container can stop cleanly.
|
|
25
|
+
*/
|
|
26
|
+
export async function runSurfaceGatewayCli(options = {}) {
|
|
27
|
+
const env = options.env ?? process.env;
|
|
28
|
+
const stderr = options.stderr ?? process.stderr;
|
|
29
|
+
const configPath = env.SURFACE_CONFIG?.trim() || DEFAULT_CONFIG;
|
|
30
|
+
const adminToken = env.SURFACE_ADMIN_TOKEN?.trim();
|
|
31
|
+
const publicBaseUrl = env.SURFACE_PUBLIC_BASE_URL?.trim() || undefined;
|
|
32
|
+
const host = env.SURFACE_HOST?.trim() || "127.0.0.1";
|
|
33
|
+
const port = numberFromEnv(env, "SURFACE_PORT", 5219);
|
|
34
|
+
const demoTenantId = env.SURFACE_DEMO_TENANT_ID?.trim() || "demo";
|
|
35
|
+
const trustProxy = booleanFromEnv(env, "SURFACE_TRUST_PROXY", false);
|
|
36
|
+
|
|
37
|
+
if (!adminToken) {
|
|
38
|
+
throw new ConfigError(
|
|
39
|
+
"SURFACE_ADMIN_TOKEN_REQUIRED",
|
|
40
|
+
"SURFACE_ADMIN_TOKEN is required. It creates page sessions and reads admin state; never expose it to browsers.",
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const config = await loadConfig(configPath);
|
|
45
|
+
const server = createSurfaceServer({
|
|
46
|
+
config,
|
|
47
|
+
adminToken,
|
|
48
|
+
publicBaseUrl,
|
|
49
|
+
host,
|
|
50
|
+
port,
|
|
51
|
+
demoTenantId,
|
|
52
|
+
trustProxy,
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
let address;
|
|
56
|
+
try {
|
|
57
|
+
address = await server.start();
|
|
58
|
+
} catch (error) {
|
|
59
|
+
throw new ConfigError(
|
|
60
|
+
"SURFACE_START_FAILED",
|
|
61
|
+
`Failed to start Surface Gateway: ${error instanceof Error ? error.message : String(error)}`,
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
stderr.write(`[surface-gateway] config ${configPath}\n`);
|
|
66
|
+
stderr.write(`[surface-gateway] page WebSocket ${address.baseUrl.replace(/^http/, "ws")}/surface\n`);
|
|
67
|
+
stderr.write(`[surface-gateway] remote MCP ${address.baseUrl}/mcp\n`);
|
|
68
|
+
|
|
69
|
+
let stopping = false;
|
|
70
|
+
async function stop(signal = "shutdown") {
|
|
71
|
+
if (stopping) return;
|
|
72
|
+
stopping = true;
|
|
73
|
+
stderr.write(`[surface-gateway] ${signal}: stopping\n`);
|
|
74
|
+
removeSignalHandlers();
|
|
75
|
+
await server.stop();
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const onSigint = () => void stop("SIGINT").catch((error) => handleStopFailure(stderr, error));
|
|
79
|
+
const onSigterm = () => void stop("SIGTERM").catch((error) => handleStopFailure(stderr, error));
|
|
80
|
+
process.once("SIGINT", onSigint);
|
|
81
|
+
process.once("SIGTERM", onSigterm);
|
|
82
|
+
|
|
83
|
+
function removeSignalHandlers() {
|
|
84
|
+
process.off("SIGINT", onSigint);
|
|
85
|
+
process.off("SIGTERM", onSigterm);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
return { server, config, configPath, ...address, stop };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function cliHelp() {
|
|
92
|
+
return [
|
|
93
|
+
"Pling Surface Gateway",
|
|
94
|
+
"",
|
|
95
|
+
"Usage: pling-surface-gateway",
|
|
96
|
+
"",
|
|
97
|
+
"Required environment:",
|
|
98
|
+
" SURFACE_ADMIN_TOKEN Server-to-server admin token",
|
|
99
|
+
"",
|
|
100
|
+
"Optional environment:",
|
|
101
|
+
" SURFACE_CONFIG JSON config path (default: bundled config.example.json)",
|
|
102
|
+
" SURFACE_PUBLIC_BASE_URL Public origin used in generated URLs",
|
|
103
|
+
" SURFACE_HOST Listen host (default: 127.0.0.1)",
|
|
104
|
+
" SURFACE_PORT Listen port (default: 5219)",
|
|
105
|
+
" SURFACE_DEMO_TENANT_ID Tenant used by the public demo route (default: demo)",
|
|
106
|
+
" SURFACE_TRUST_PROXY Set to 1 only behind a trusted proxy that overwrites X-Forwarded-For",
|
|
107
|
+
"",
|
|
108
|
+
].join("\n");
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function numberFromEnv(env, name, fallback) {
|
|
112
|
+
const value = env[name];
|
|
113
|
+
if (!value) return fallback;
|
|
114
|
+
const number = Number(value);
|
|
115
|
+
if (!Number.isInteger(number) || number < 1 || number > 65535) {
|
|
116
|
+
throw new ConfigError("CONFIG_INVALID", `${name} must be a TCP port between 1 and 65535.`);
|
|
117
|
+
}
|
|
118
|
+
return number;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function booleanFromEnv(env, name, fallback) {
|
|
122
|
+
const value = env[name]?.trim().toLowerCase();
|
|
123
|
+
if (!value) return fallback;
|
|
124
|
+
if (["1", "true", "yes", "on"].includes(value)) return true;
|
|
125
|
+
if (["0", "false", "no", "off"].includes(value)) return false;
|
|
126
|
+
throw new ConfigError("CONFIG_INVALID", `${name} must be 1/0, true/false, yes/no, or on/off.`);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function handleStopFailure(stderr, error) {
|
|
130
|
+
stderr.write(`[surface-gateway] shutdown failed: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
131
|
+
process.exitCode = 1;
|
|
132
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
{
|
|
2
|
+
"tenants": [
|
|
3
|
+
{
|
|
4
|
+
"id": "demo",
|
|
5
|
+
"displayName": "Pling Todo Demo",
|
|
6
|
+
"origins": [
|
|
7
|
+
"http://127.0.0.1:5220",
|
|
8
|
+
"http://localhost:5220",
|
|
9
|
+
"http://127.0.0.1:5191",
|
|
10
|
+
"http://localhost:5191",
|
|
11
|
+
"https://todo.plingjs.dev",
|
|
12
|
+
"https://plingjs.dev"
|
|
13
|
+
],
|
|
14
|
+
"maxPageSessionTtlMs": 86400000,
|
|
15
|
+
"maxAgentSessionTtlMs": 86400000,
|
|
16
|
+
"publicDemo": {
|
|
17
|
+
"origins": ["http://127.0.0.1:5191", "http://localhost:5191", "https://plingjs.dev"],
|
|
18
|
+
"scope": [
|
|
19
|
+
"todo.overview",
|
|
20
|
+
"todo.add",
|
|
21
|
+
"todo.update",
|
|
22
|
+
"todo.toggle",
|
|
23
|
+
"todo.delete",
|
|
24
|
+
"todo.clear_completed"
|
|
25
|
+
],
|
|
26
|
+
"pageSessionTtlMs": 86400000,
|
|
27
|
+
"maxSessionsPerWindow": 30,
|
|
28
|
+
"windowMs": 600000,
|
|
29
|
+
"maxActiveSessions": 40
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
]
|
|
33
|
+
}
|