@otwdesign/db-node 0.0.0-stage → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +2 -0
- package/README.md +18 -2
- package/dist/cli.d.ts +23 -0
- package/dist/cli.js +114 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.d.ts +49 -0
- package/dist/index.js +131 -0
- package/dist/index.js.map +1 -0
- package/package.json +62 -3
- package/src/cli.ts +139 -0
- package/src/index.ts +172 -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,19 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @otwdesign/db-node
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
OTW DB in Node servers: node:http, Express, Connect, Fastify and Koa.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npm install @otwdesign/db-node @otwdesign/db-core pg pg-cursor
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { fastifyPlugin, koaMiddleware, toNodeHandler } from '@otwdesign/db-node'
|
|
11
|
+
|
|
12
|
+
app.use('/db', toNodeHandler(dbAdmin)) // Express or Connect
|
|
13
|
+
http.createServer(toNodeHandler(dbAdmin)) // node:http
|
|
14
|
+
await fastify.register(fastifyPlugin(dbAdmin)) // Fastify
|
|
15
|
+
koa.use(koaMiddleware(dbAdmin)) // Koa
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
`dbAdmin` comes from `createDbAdmin()` in `@otwdesign/db-core`. The whole guide:
|
|
19
|
+
[github.com/OTWSRL/otw-db](https://github.com/OTWSRL/otw-db#readme).
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { type ConnectionConfig } from '@otwdesign/db-core';
|
|
2
|
+
export interface ServerOptions {
|
|
3
|
+
connections: readonly ConnectionConfig[];
|
|
4
|
+
/** Default 4010; 0 picks a free port. */
|
|
5
|
+
port?: number;
|
|
6
|
+
/** Default 127.0.0.1: only this machine. */
|
|
7
|
+
host?: string;
|
|
8
|
+
/** Generated when not given. */
|
|
9
|
+
token?: string;
|
|
10
|
+
}
|
|
11
|
+
export interface RunningServer {
|
|
12
|
+
/** Opening it signs the browser in. */
|
|
13
|
+
url: string;
|
|
14
|
+
token: string;
|
|
15
|
+
close(): Promise<void>;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* OTW DB on its own HTTP server. Anyone with the token may use it, so it listens on this machine
|
|
19
|
+
* only unless told otherwise; the link it prints signs the browser in with an HttpOnly cookie.
|
|
20
|
+
*/
|
|
21
|
+
export declare function startServer(options: ServerOptions): Promise<RunningServer>;
|
|
22
|
+
/** The `otw-db` command. */
|
|
23
|
+
export declare function main(argv?: string[]): Promise<void>;
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { randomBytes, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import { existsSync } from 'node:fs';
|
|
3
|
+
import { createServer } from 'node:http';
|
|
4
|
+
import { parseArgs } from 'node:util';
|
|
5
|
+
import { connectionsFromEnv, createDbAdmin } from '@otwdesign/db-core';
|
|
6
|
+
import { toNodeHandler } from "./index.js";
|
|
7
|
+
const COOKIE = 'otw_db_token';
|
|
8
|
+
/**
|
|
9
|
+
* OTW DB on its own HTTP server. Anyone with the token may use it, so it listens on this machine
|
|
10
|
+
* only unless told otherwise; the link it prints signs the browser in with an HttpOnly cookie.
|
|
11
|
+
*/
|
|
12
|
+
export async function startServer(options) {
|
|
13
|
+
const token = options.token ?? randomBytes(24).toString('base64url');
|
|
14
|
+
const admin = createDbAdmin({
|
|
15
|
+
connections: options.connections,
|
|
16
|
+
authorize: (request) => (holdsToken(request, token) ? { id: 'local' } : null),
|
|
17
|
+
});
|
|
18
|
+
const handle = toNodeHandler(admin);
|
|
19
|
+
const server = createServer((req, res) => {
|
|
20
|
+
const url = new URL(req.url ?? '/', 'http://localhost');
|
|
21
|
+
const given = url.searchParams.get('token');
|
|
22
|
+
if (given !== null) {
|
|
23
|
+
url.searchParams.delete('token');
|
|
24
|
+
const back = `${url.pathname}${url.search}`;
|
|
25
|
+
res.statusCode = 303;
|
|
26
|
+
res.setHeader('location', back);
|
|
27
|
+
if (same(given, token)) {
|
|
28
|
+
res.setHeader('set-cookie', `${COOKIE}=${token}; HttpOnly; SameSite=Strict; Path=/`);
|
|
29
|
+
}
|
|
30
|
+
res.end();
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
void handle(req, res);
|
|
34
|
+
});
|
|
35
|
+
await listen(server, options.port ?? 4010, options.host ?? '127.0.0.1');
|
|
36
|
+
const { port, address } = server.address();
|
|
37
|
+
const host = address.includes(':') ? `[${address}]` : address;
|
|
38
|
+
return {
|
|
39
|
+
url: `http://${host}:${port}/?token=${token}`,
|
|
40
|
+
token,
|
|
41
|
+
async close() {
|
|
42
|
+
await new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())));
|
|
43
|
+
await admin.close();
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
function listen(server, port, host) {
|
|
48
|
+
return new Promise((resolve, reject) => {
|
|
49
|
+
server.once('error', reject);
|
|
50
|
+
server.listen(port, host, () => {
|
|
51
|
+
server.off('error', reject);
|
|
52
|
+
resolve();
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
function holdsToken(request, token) {
|
|
57
|
+
const bearer = request.headers.get('authorization')?.match(/^Bearer (.+)$/)?.[1];
|
|
58
|
+
const cookie = request.headers
|
|
59
|
+
.get('cookie')
|
|
60
|
+
?.split(';')
|
|
61
|
+
.map((part) => part.trim().split('='))
|
|
62
|
+
.find(([name]) => name === COOKIE)?.[1];
|
|
63
|
+
return [bearer, cookie].some((given) => given !== undefined && same(given, token));
|
|
64
|
+
}
|
|
65
|
+
function same(given, token) {
|
|
66
|
+
const a = Buffer.from(given);
|
|
67
|
+
const b = Buffer.from(token);
|
|
68
|
+
return a.length === b.length && timingSafeEqual(a, b);
|
|
69
|
+
}
|
|
70
|
+
const HELP = `otw-db: a database manager in your browser
|
|
71
|
+
|
|
72
|
+
Usage: otw-db [--port 4010] [--host 127.0.0.1] [--env-file .env]
|
|
73
|
+
|
|
74
|
+
Connections come from the environment (and .env, when there is one):
|
|
75
|
+
DB_ADMIN_<NAME>_URL postgres://user:password@host:5432/db
|
|
76
|
+
DB_ADMIN_<NAME>_ACCESS read (default) or write
|
|
77
|
+
DB_ADMIN_<NAME>_LABEL shown instead of the name
|
|
78
|
+
DB_ADMIN_<NAME>_TAG local, development, testing, staging or production
|
|
79
|
+
`;
|
|
80
|
+
/** The `otw-db` command. */
|
|
81
|
+
export async function main(argv = process.argv.slice(2)) {
|
|
82
|
+
const { values } = parseArgs({
|
|
83
|
+
args: argv,
|
|
84
|
+
options: {
|
|
85
|
+
port: { type: 'string', default: '4010' },
|
|
86
|
+
host: { type: 'string', default: '127.0.0.1' },
|
|
87
|
+
'env-file': { type: 'string' },
|
|
88
|
+
help: { type: 'boolean', short: 'h' },
|
|
89
|
+
},
|
|
90
|
+
});
|
|
91
|
+
if (values.help) {
|
|
92
|
+
process.stdout.write(HELP);
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
const envFile = values['env-file'] ?? (existsSync('.env') ? '.env' : undefined);
|
|
96
|
+
if (envFile)
|
|
97
|
+
process.loadEnvFile(envFile);
|
|
98
|
+
const connections = connectionsFromEnv();
|
|
99
|
+
if (!connections.length) {
|
|
100
|
+
process.stderr.write(`No connections: set DB_ADMIN_<NAME>_URL.\n\n${HELP}`);
|
|
101
|
+
process.exitCode = 1;
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
const port = Number(values.port);
|
|
105
|
+
if (!Number.isInteger(port) || port < 0 || port > 65_535) {
|
|
106
|
+
throw new Error(`--port is a port number, not "${values.port}".`);
|
|
107
|
+
}
|
|
108
|
+
const server = await startServer({ connections, port, host: values.host });
|
|
109
|
+
process.stdout.write(`OTW DB is running. Open ${server.url}\n`);
|
|
110
|
+
const stop = () => void server.close().then(() => process.exit(0));
|
|
111
|
+
process.once('SIGINT', stop);
|
|
112
|
+
process.once('SIGTERM', stop);
|
|
113
|
+
}
|
|
114
|
+
//# sourceMappingURL=cli.js.map
|
package/dist/cli.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAC1D,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AACpC,OAAO,EAAE,YAAY,EAAe,MAAM,WAAW,CAAA;AAErD,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAA;AACrC,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAyB,MAAM,oBAAoB,CAAA;AAC7F,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAE1C,MAAM,MAAM,GAAG,cAAc,CAAA;AAmB7B;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,OAAsB;IACtD,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,IAAI,WAAW,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAA;IACpE,MAAM,KAAK,GAAG,aAAa,CAAC;QAC1B,WAAW,EAAE,OAAO,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CAAA;IAClE,OAAO,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAA;IAC5B,OAAO,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAA;AAC/B,CAAC"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
import type { DbAdmin } from '@otwdesign/db-core';
|
|
3
|
+
/** Express's and Connect's `next`: called for paths outside the base path, and with errors. */
|
|
4
|
+
export type Next = (error?: unknown) => void;
|
|
5
|
+
/** A node:http-style handler, as Express, Connect and `http.createServer` take. It resolves once the response is sent. */
|
|
6
|
+
export type NodeHandler = (request: IncomingMessage, response: ServerResponse, next?: Next) => Promise<void>;
|
|
7
|
+
/**
|
|
8
|
+
* The Fetch handler for node:http servers. Paths outside the admin's base path go to `next`
|
|
9
|
+
* when there is one (Express, Connect), and get a 404 otherwise. A body a body-parser already
|
|
10
|
+
* read (`express.json()`) is passed on as it parsed it.
|
|
11
|
+
*/
|
|
12
|
+
export declare function toNodeHandler(admin: Pick<DbAdmin, 'fetch' | 'basePath'>): NodeHandler;
|
|
13
|
+
/** A Fetch Request for the Node one: its URL, headers and body, aborted if the browser leaves. */
|
|
14
|
+
export declare function toRequest(req: IncomingMessage, res: ServerResponse, path?: string): Request;
|
|
15
|
+
/** Writes a Fetch Response to a Node one, streaming its body. */
|
|
16
|
+
export declare function send(res: ServerResponse, response: Response): Promise<void>;
|
|
17
|
+
/** What the Fastify plugin uses of Fastify: shapes only, so this package needs no fastify. */
|
|
18
|
+
interface FastifyLike {
|
|
19
|
+
removeAllContentTypeParsers(): void;
|
|
20
|
+
addContentTypeParser(type: string, parser: (request: unknown, payload: unknown, done: (error: Error | null, body?: unknown) => void) => void): void;
|
|
21
|
+
all(path: string, handler: (request: {
|
|
22
|
+
raw: IncomingMessage;
|
|
23
|
+
}, reply: {
|
|
24
|
+
raw: ServerResponse;
|
|
25
|
+
hijack(): void;
|
|
26
|
+
}) => Promise<void>): void;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* A Fastify plugin: `app.register(fastifyPlugin(dbAdmin))`. Its routes leave the body unread,
|
|
30
|
+
* as Fastify's own parsers would read it first, and answer through Node's response. Register it
|
|
31
|
+
* as it is, not through fastify-plugin, so its parser settings stay inside it.
|
|
32
|
+
*/
|
|
33
|
+
export declare function fastifyPlugin(admin: Pick<DbAdmin, 'fetch' | 'basePath'>): (fastify: FastifyLike) => Promise<void>;
|
|
34
|
+
/** What the Koa middleware uses of Koa's context. */
|
|
35
|
+
interface KoaContext {
|
|
36
|
+
path: string;
|
|
37
|
+
req: IncomingMessage;
|
|
38
|
+
res: ServerResponse;
|
|
39
|
+
respond?: boolean;
|
|
40
|
+
request: {
|
|
41
|
+
body?: unknown;
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Koa middleware: `app.use(koaMiddleware(dbAdmin))`. Paths outside the base path go on to the
|
|
46
|
+
* next middleware. A body a parser before it read (koa-bodyparser) is handed over.
|
|
47
|
+
*/
|
|
48
|
+
export declare function koaMiddleware(admin: Pick<DbAdmin, 'fetch' | 'basePath'>): (ctx: KoaContext, next: () => Promise<unknown>) => Promise<unknown>;
|
|
49
|
+
export {};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { Readable } from 'node:stream';
|
|
2
|
+
import { pipeline } from 'node:stream/promises';
|
|
3
|
+
/**
|
|
4
|
+
* The Fetch handler for node:http servers. Paths outside the admin's base path go to `next`
|
|
5
|
+
* when there is one (Express, Connect), and get a 404 otherwise. A body a body-parser already
|
|
6
|
+
* read (`express.json()`) is passed on as it parsed it.
|
|
7
|
+
*/
|
|
8
|
+
export function toNodeHandler(admin) {
|
|
9
|
+
return async (req, res, next) => {
|
|
10
|
+
try {
|
|
11
|
+
// Express strips its mount path from `url` and keeps the whole one in `originalUrl`.
|
|
12
|
+
const path = req.originalUrl ?? req.url ?? '/';
|
|
13
|
+
if (!within(path, admin.basePath)) {
|
|
14
|
+
if (next)
|
|
15
|
+
return next();
|
|
16
|
+
res.statusCode = 404;
|
|
17
|
+
res.end();
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
await send(res, await admin.fetch(toRequest(req, res, path)));
|
|
21
|
+
}
|
|
22
|
+
catch (error) {
|
|
23
|
+
// The browser went away mid-response: nothing left to tell it.
|
|
24
|
+
if (res.destroyed)
|
|
25
|
+
return;
|
|
26
|
+
if (next)
|
|
27
|
+
return next(error);
|
|
28
|
+
console.error('otw-db: a request failed', error);
|
|
29
|
+
if (res.headersSent)
|
|
30
|
+
res.destroy(error);
|
|
31
|
+
else {
|
|
32
|
+
res.statusCode = 500;
|
|
33
|
+
res.end();
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
function within(path, basePath) {
|
|
39
|
+
if (!basePath)
|
|
40
|
+
return true;
|
|
41
|
+
const pathname = path.split('?', 1)[0];
|
|
42
|
+
return pathname === basePath || pathname.startsWith(`${basePath}/`);
|
|
43
|
+
}
|
|
44
|
+
/** A Fetch Request for the Node one: its URL, headers and body, aborted if the browser leaves. */
|
|
45
|
+
export function toRequest(req, res, path = req.url ?? '/') {
|
|
46
|
+
const protocol = req.socket.encrypted ? 'https' : 'http';
|
|
47
|
+
const url = new URL(path, `${protocol}://${req.headers.host ?? 'localhost'}`);
|
|
48
|
+
const headers = new Headers();
|
|
49
|
+
for (const [name, value] of Object.entries(req.headers)) {
|
|
50
|
+
if (value === undefined)
|
|
51
|
+
continue;
|
|
52
|
+
for (const one of Array.isArray(value) ? value : [value])
|
|
53
|
+
headers.append(name, one);
|
|
54
|
+
}
|
|
55
|
+
const controller = new AbortController();
|
|
56
|
+
res.once('close', () => {
|
|
57
|
+
if (!res.writableFinished)
|
|
58
|
+
controller.abort();
|
|
59
|
+
});
|
|
60
|
+
const method = req.method ?? 'GET';
|
|
61
|
+
const init = { method, headers, signal: controller.signal };
|
|
62
|
+
if (method !== 'GET' && method !== 'HEAD') {
|
|
63
|
+
if (req.readableEnded) {
|
|
64
|
+
// Read already, by a body parser: what it parsed is all there is.
|
|
65
|
+
const parsed = req.body;
|
|
66
|
+
headers.delete('content-length');
|
|
67
|
+
if (parsed !== undefined) {
|
|
68
|
+
init.body =
|
|
69
|
+
typeof parsed === 'string' || parsed instanceof Uint8Array
|
|
70
|
+
? parsed
|
|
71
|
+
: JSON.stringify(parsed);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
else {
|
|
75
|
+
init.body = Readable.toWeb(req);
|
|
76
|
+
init.duplex = 'half';
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return new Request(url, init);
|
|
80
|
+
}
|
|
81
|
+
/** Writes a Fetch Response to a Node one, streaming its body. */
|
|
82
|
+
export async function send(res, response) {
|
|
83
|
+
res.statusCode = response.status;
|
|
84
|
+
for (const [name, value] of response.headers) {
|
|
85
|
+
if (name !== 'set-cookie')
|
|
86
|
+
res.setHeader(name, value);
|
|
87
|
+
}
|
|
88
|
+
const cookies = response.headers.getSetCookie();
|
|
89
|
+
if (cookies.length)
|
|
90
|
+
res.setHeader('set-cookie', cookies);
|
|
91
|
+
if (!response.body) {
|
|
92
|
+
res.end();
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
await pipeline(Readable.fromWeb(response.body), res);
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* A Fastify plugin: `app.register(fastifyPlugin(dbAdmin))`. Its routes leave the body unread,
|
|
99
|
+
* as Fastify's own parsers would read it first, and answer through Node's response. Register it
|
|
100
|
+
* as it is, not through fastify-plugin, so its parser settings stay inside it.
|
|
101
|
+
*/
|
|
102
|
+
export function fastifyPlugin(admin) {
|
|
103
|
+
const handle = toNodeHandler(admin);
|
|
104
|
+
return async function otwDb(fastify) {
|
|
105
|
+
fastify.removeAllContentTypeParsers();
|
|
106
|
+
fastify.addContentTypeParser('*', (_request, _payload, done) => done(null));
|
|
107
|
+
const route = async (request, reply) => {
|
|
108
|
+
reply.hijack();
|
|
109
|
+
await handle(request.raw, reply.raw);
|
|
110
|
+
};
|
|
111
|
+
fastify.all(admin.basePath || '/', route);
|
|
112
|
+
fastify.all(`${admin.basePath}/*`, route);
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Koa middleware: `app.use(koaMiddleware(dbAdmin))`. Paths outside the base path go on to the
|
|
117
|
+
* next middleware. A body a parser before it read (koa-bodyparser) is handed over.
|
|
118
|
+
*/
|
|
119
|
+
export function koaMiddleware(admin) {
|
|
120
|
+
const handle = toNodeHandler(admin);
|
|
121
|
+
return async (ctx, next) => {
|
|
122
|
+
if (!within(ctx.path, admin.basePath))
|
|
123
|
+
return next();
|
|
124
|
+
const req = ctx.req;
|
|
125
|
+
if (req.readableEnded && req.body === undefined)
|
|
126
|
+
req.body = ctx.request.body;
|
|
127
|
+
ctx.respond = false;
|
|
128
|
+
await handle(ctx.req, ctx.res);
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAA;AACtC,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAA;AAc/C;;;;GAIG;AACH,MAAM,UAAU,aAAa,CAAC,KAA0C;IACtE,OAAO,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QAC9B,IAAI,CAAC;YACH,qFAAqF;YACrF,MAAM,IAAI,GAAI,GAAkD,CAAC,WAAW,IAAI,GAAG,CAAC,GAAG,IAAI,GAAG,CAAA;YAC9F,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC;gBACl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2
|
"name": "@otwdesign/db-node",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.0.1",
|
|
4
|
+
"description": "OTW DB for Node servers: node:http, Express, Connect, Fastify and Koa; Hono, Bun and Deno take db-core's Fetch handler as it is.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"author": "OTW SRL",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/OTWSRL/otw-db.git",
|
|
10
|
+
"directory": "packages/node"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/OTWSRL/otw-db/tree/main/packages/node#readme",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/OTWSRL/otw-db/issues"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"database",
|
|
18
|
+
"admin",
|
|
19
|
+
"express",
|
|
20
|
+
"fastify",
|
|
21
|
+
"koa"
|
|
22
|
+
],
|
|
23
|
+
"publishConfig": {
|
|
24
|
+
"access": "public"
|
|
25
|
+
},
|
|
26
|
+
"type": "module",
|
|
27
|
+
"engines": {
|
|
28
|
+
"node": ">=22.18"
|
|
29
|
+
},
|
|
30
|
+
"exports": {
|
|
31
|
+
".": {
|
|
32
|
+
"@otwdesign/source": "./src/index.ts",
|
|
33
|
+
"types": "./dist/index.d.ts",
|
|
34
|
+
"default": "./dist/index.js"
|
|
35
|
+
},
|
|
36
|
+
"./cli": {
|
|
37
|
+
"@otwdesign/source": "./src/cli.ts",
|
|
38
|
+
"types": "./dist/cli.d.ts",
|
|
39
|
+
"default": "./dist/cli.js"
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
"files": [
|
|
43
|
+
"dist",
|
|
44
|
+
"src",
|
|
45
|
+
"NOTICE"
|
|
46
|
+
],
|
|
47
|
+
"dependencies": {
|
|
48
|
+
"@otwdesign/db-core": "1.0.1"
|
|
49
|
+
},
|
|
50
|
+
"devDependencies": {
|
|
51
|
+
"@types/express": "^5.0.6",
|
|
52
|
+
"express": "^5.3.0",
|
|
53
|
+
"fastify": "^5.12.8",
|
|
54
|
+
"koa": "^3.3.0",
|
|
55
|
+
"@types/koa": "^3.0.3",
|
|
56
|
+
"koa-bodyparser": "^4.4.1",
|
|
57
|
+
"@types/koa-bodyparser": "^4.3.13",
|
|
58
|
+
"hono": "^4.13.16",
|
|
59
|
+
"@hono/node-server": "^2.1.6"
|
|
60
|
+
},
|
|
61
|
+
"scripts": {
|
|
62
|
+
"build": "tsc -p tsconfig.build.json",
|
|
63
|
+
"typecheck": "tsc -p tsconfig.json --noEmit"
|
|
64
|
+
}
|
|
6
65
|
}
|
package/src/cli.ts
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { randomBytes, timingSafeEqual } from 'node:crypto'
|
|
2
|
+
import { existsSync } from 'node:fs'
|
|
3
|
+
import { createServer, type Server } from 'node:http'
|
|
4
|
+
import type { AddressInfo } from 'node:net'
|
|
5
|
+
import { parseArgs } from 'node:util'
|
|
6
|
+
import { connectionsFromEnv, createDbAdmin, type ConnectionConfig } from '@otwdesign/db-core'
|
|
7
|
+
import { toNodeHandler } from './index.ts'
|
|
8
|
+
|
|
9
|
+
const COOKIE = 'otw_db_token'
|
|
10
|
+
|
|
11
|
+
export interface ServerOptions {
|
|
12
|
+
connections: readonly ConnectionConfig[]
|
|
13
|
+
/** Default 4010; 0 picks a free port. */
|
|
14
|
+
port?: number
|
|
15
|
+
/** Default 127.0.0.1: only this machine. */
|
|
16
|
+
host?: string
|
|
17
|
+
/** Generated when not given. */
|
|
18
|
+
token?: string
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface RunningServer {
|
|
22
|
+
/** Opening it signs the browser in. */
|
|
23
|
+
url: string
|
|
24
|
+
token: string
|
|
25
|
+
close(): Promise<void>
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* OTW DB on its own HTTP server. Anyone with the token may use it, so it listens on this machine
|
|
30
|
+
* only unless told otherwise; the link it prints signs the browser in with an HttpOnly cookie.
|
|
31
|
+
*/
|
|
32
|
+
export async function startServer(options: ServerOptions): Promise<RunningServer> {
|
|
33
|
+
const token = options.token ?? randomBytes(24).toString('base64url')
|
|
34
|
+
const admin = createDbAdmin({
|
|
35
|
+
connections: options.connections,
|
|
36
|
+
authorize: (request) => (holdsToken(request, token) ? { id: 'local' } : null),
|
|
37
|
+
})
|
|
38
|
+
const handle = toNodeHandler(admin)
|
|
39
|
+
const server = createServer((req, res) => {
|
|
40
|
+
const url = new URL(req.url ?? '/', 'http://localhost')
|
|
41
|
+
const given = url.searchParams.get('token')
|
|
42
|
+
if (given !== null) {
|
|
43
|
+
url.searchParams.delete('token')
|
|
44
|
+
const back = `${url.pathname}${url.search}`
|
|
45
|
+
res.statusCode = 303
|
|
46
|
+
res.setHeader('location', back)
|
|
47
|
+
if (same(given, token)) {
|
|
48
|
+
res.setHeader('set-cookie', `${COOKIE}=${token}; HttpOnly; SameSite=Strict; Path=/`)
|
|
49
|
+
}
|
|
50
|
+
res.end()
|
|
51
|
+
return
|
|
52
|
+
}
|
|
53
|
+
void handle(req, res)
|
|
54
|
+
})
|
|
55
|
+
await listen(server, options.port ?? 4010, options.host ?? '127.0.0.1')
|
|
56
|
+
const { port, address } = server.address() as AddressInfo
|
|
57
|
+
const host = address.includes(':') ? `[${address}]` : address
|
|
58
|
+
return {
|
|
59
|
+
url: `http://${host}:${port}/?token=${token}`,
|
|
60
|
+
token,
|
|
61
|
+
async close() {
|
|
62
|
+
await new Promise<void>((resolve, reject) =>
|
|
63
|
+
server.close((error) => (error ? reject(error) : resolve())),
|
|
64
|
+
)
|
|
65
|
+
await admin.close()
|
|
66
|
+
},
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function listen(server: Server, port: number, host: string): Promise<void> {
|
|
71
|
+
return new Promise((resolve, reject) => {
|
|
72
|
+
server.once('error', reject)
|
|
73
|
+
server.listen(port, host, () => {
|
|
74
|
+
server.off('error', reject)
|
|
75
|
+
resolve()
|
|
76
|
+
})
|
|
77
|
+
})
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function holdsToken(request: Request, token: string): boolean {
|
|
81
|
+
const bearer = request.headers.get('authorization')?.match(/^Bearer (.+)$/)?.[1]
|
|
82
|
+
const cookie = request.headers
|
|
83
|
+
.get('cookie')
|
|
84
|
+
?.split(';')
|
|
85
|
+
.map((part) => part.trim().split('='))
|
|
86
|
+
.find(([name]) => name === COOKIE)?.[1]
|
|
87
|
+
return [bearer, cookie].some((given) => given !== undefined && same(given, token))
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function same(given: string, token: string): boolean {
|
|
91
|
+
const a = Buffer.from(given)
|
|
92
|
+
const b = Buffer.from(token)
|
|
93
|
+
return a.length === b.length && timingSafeEqual(a, b)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const HELP = `otw-db: a database manager in your browser
|
|
97
|
+
|
|
98
|
+
Usage: otw-db [--port 4010] [--host 127.0.0.1] [--env-file .env]
|
|
99
|
+
|
|
100
|
+
Connections come from the environment (and .env, when there is one):
|
|
101
|
+
DB_ADMIN_<NAME>_URL postgres://user:password@host:5432/db
|
|
102
|
+
DB_ADMIN_<NAME>_ACCESS read (default) or write
|
|
103
|
+
DB_ADMIN_<NAME>_LABEL shown instead of the name
|
|
104
|
+
DB_ADMIN_<NAME>_TAG local, development, testing, staging or production
|
|
105
|
+
`
|
|
106
|
+
|
|
107
|
+
/** The `otw-db` command. */
|
|
108
|
+
export async function main(argv = process.argv.slice(2)): Promise<void> {
|
|
109
|
+
const { values } = parseArgs({
|
|
110
|
+
args: argv,
|
|
111
|
+
options: {
|
|
112
|
+
port: { type: 'string', default: '4010' },
|
|
113
|
+
host: { type: 'string', default: '127.0.0.1' },
|
|
114
|
+
'env-file': { type: 'string' },
|
|
115
|
+
help: { type: 'boolean', short: 'h' },
|
|
116
|
+
},
|
|
117
|
+
})
|
|
118
|
+
if (values.help) {
|
|
119
|
+
process.stdout.write(HELP)
|
|
120
|
+
return
|
|
121
|
+
}
|
|
122
|
+
const envFile = values['env-file'] ?? (existsSync('.env') ? '.env' : undefined)
|
|
123
|
+
if (envFile) process.loadEnvFile(envFile)
|
|
124
|
+
const connections = connectionsFromEnv()
|
|
125
|
+
if (!connections.length) {
|
|
126
|
+
process.stderr.write(`No connections: set DB_ADMIN_<NAME>_URL.\n\n${HELP}`)
|
|
127
|
+
process.exitCode = 1
|
|
128
|
+
return
|
|
129
|
+
}
|
|
130
|
+
const port = Number(values.port)
|
|
131
|
+
if (!Number.isInteger(port) || port < 0 || port > 65_535) {
|
|
132
|
+
throw new Error(`--port is a port number, not "${values.port}".`)
|
|
133
|
+
}
|
|
134
|
+
const server = await startServer({ connections, port, host: values.host })
|
|
135
|
+
process.stdout.write(`OTW DB is running. Open ${server.url}\n`)
|
|
136
|
+
const stop = () => void server.close().then(() => process.exit(0))
|
|
137
|
+
process.once('SIGINT', stop)
|
|
138
|
+
process.once('SIGTERM', stop)
|
|
139
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'node:http'
|
|
2
|
+
import type { TLSSocket } from 'node:tls'
|
|
3
|
+
import { Readable } from 'node:stream'
|
|
4
|
+
import { pipeline } from 'node:stream/promises'
|
|
5
|
+
import type { ReadableStream as NodeReadableStream } from 'node:stream/web'
|
|
6
|
+
import type { DbAdmin } from '@otwdesign/db-core'
|
|
7
|
+
|
|
8
|
+
/** Express's and Connect's `next`: called for paths outside the base path, and with errors. */
|
|
9
|
+
export type Next = (error?: unknown) => void
|
|
10
|
+
|
|
11
|
+
/** A node:http-style handler, as Express, Connect and `http.createServer` take. It resolves once the response is sent. */
|
|
12
|
+
export type NodeHandler = (
|
|
13
|
+
request: IncomingMessage,
|
|
14
|
+
response: ServerResponse,
|
|
15
|
+
next?: Next,
|
|
16
|
+
) => Promise<void>
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The Fetch handler for node:http servers. Paths outside the admin's base path go to `next`
|
|
20
|
+
* when there is one (Express, Connect), and get a 404 otherwise. A body a body-parser already
|
|
21
|
+
* read (`express.json()`) is passed on as it parsed it.
|
|
22
|
+
*/
|
|
23
|
+
export function toNodeHandler(admin: Pick<DbAdmin, 'fetch' | 'basePath'>): NodeHandler {
|
|
24
|
+
return async (req, res, next) => {
|
|
25
|
+
try {
|
|
26
|
+
// Express strips its mount path from `url` and keeps the whole one in `originalUrl`.
|
|
27
|
+
const path = (req as IncomingMessage & { originalUrl?: string }).originalUrl ?? req.url ?? '/'
|
|
28
|
+
if (!within(path, admin.basePath)) {
|
|
29
|
+
if (next) return next()
|
|
30
|
+
res.statusCode = 404
|
|
31
|
+
res.end()
|
|
32
|
+
return
|
|
33
|
+
}
|
|
34
|
+
await send(res, await admin.fetch(toRequest(req, res, path)))
|
|
35
|
+
} catch (error) {
|
|
36
|
+
// The browser went away mid-response: nothing left to tell it.
|
|
37
|
+
if (res.destroyed) return
|
|
38
|
+
if (next) return next(error)
|
|
39
|
+
console.error('otw-db: a request failed', error)
|
|
40
|
+
if (res.headersSent) res.destroy(error as Error)
|
|
41
|
+
else {
|
|
42
|
+
res.statusCode = 500
|
|
43
|
+
res.end()
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function within(path: string, basePath: string): boolean {
|
|
50
|
+
if (!basePath) return true
|
|
51
|
+
const pathname = path.split('?', 1)[0]!
|
|
52
|
+
return pathname === basePath || pathname.startsWith(`${basePath}/`)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** A Fetch Request for the Node one: its URL, headers and body, aborted if the browser leaves. */
|
|
56
|
+
export function toRequest(
|
|
57
|
+
req: IncomingMessage,
|
|
58
|
+
res: ServerResponse,
|
|
59
|
+
path = req.url ?? '/',
|
|
60
|
+
): Request {
|
|
61
|
+
const protocol = (req.socket as TLSSocket).encrypted ? 'https' : 'http'
|
|
62
|
+
const url = new URL(path, `${protocol}://${req.headers.host ?? 'localhost'}`)
|
|
63
|
+
const headers = new Headers()
|
|
64
|
+
for (const [name, value] of Object.entries(req.headers)) {
|
|
65
|
+
if (value === undefined) continue
|
|
66
|
+
for (const one of Array.isArray(value) ? value : [value]) headers.append(name, one)
|
|
67
|
+
}
|
|
68
|
+
const controller = new AbortController()
|
|
69
|
+
res.once('close', () => {
|
|
70
|
+
if (!res.writableFinished) controller.abort()
|
|
71
|
+
})
|
|
72
|
+
const method = req.method ?? 'GET'
|
|
73
|
+
const init: RequestInit & { duplex?: 'half' } = { method, headers, signal: controller.signal }
|
|
74
|
+
if (method !== 'GET' && method !== 'HEAD') {
|
|
75
|
+
if (req.readableEnded) {
|
|
76
|
+
// Read already, by a body parser: what it parsed is all there is.
|
|
77
|
+
const parsed = (req as IncomingMessage & { body?: unknown }).body
|
|
78
|
+
headers.delete('content-length')
|
|
79
|
+
if (parsed !== undefined) {
|
|
80
|
+
init.body =
|
|
81
|
+
typeof parsed === 'string' || parsed instanceof Uint8Array
|
|
82
|
+
? (parsed as BodyInit)
|
|
83
|
+
: JSON.stringify(parsed)
|
|
84
|
+
}
|
|
85
|
+
} else {
|
|
86
|
+
init.body = Readable.toWeb(req) as ReadableStream<Uint8Array>
|
|
87
|
+
init.duplex = 'half'
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return new Request(url, init)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Writes a Fetch Response to a Node one, streaming its body. */
|
|
94
|
+
export async function send(res: ServerResponse, response: Response): Promise<void> {
|
|
95
|
+
res.statusCode = response.status
|
|
96
|
+
for (const [name, value] of response.headers) {
|
|
97
|
+
if (name !== 'set-cookie') res.setHeader(name, value)
|
|
98
|
+
}
|
|
99
|
+
const cookies = response.headers.getSetCookie()
|
|
100
|
+
if (cookies.length) res.setHeader('set-cookie', cookies)
|
|
101
|
+
if (!response.body) {
|
|
102
|
+
res.end()
|
|
103
|
+
return
|
|
104
|
+
}
|
|
105
|
+
await pipeline(Readable.fromWeb(response.body as NodeReadableStream), res)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** What the Fastify plugin uses of Fastify: shapes only, so this package needs no fastify. */
|
|
109
|
+
interface FastifyLike {
|
|
110
|
+
removeAllContentTypeParsers(): void
|
|
111
|
+
addContentTypeParser(
|
|
112
|
+
type: string,
|
|
113
|
+
parser: (
|
|
114
|
+
request: unknown,
|
|
115
|
+
payload: unknown,
|
|
116
|
+
done: (error: Error | null, body?: unknown) => void,
|
|
117
|
+
) => void,
|
|
118
|
+
): void
|
|
119
|
+
all(
|
|
120
|
+
path: string,
|
|
121
|
+
handler: (
|
|
122
|
+
request: { raw: IncomingMessage },
|
|
123
|
+
reply: { raw: ServerResponse; hijack(): void },
|
|
124
|
+
) => Promise<void>,
|
|
125
|
+
): void
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* A Fastify plugin: `app.register(fastifyPlugin(dbAdmin))`. Its routes leave the body unread,
|
|
130
|
+
* as Fastify's own parsers would read it first, and answer through Node's response. Register it
|
|
131
|
+
* as it is, not through fastify-plugin, so its parser settings stay inside it.
|
|
132
|
+
*/
|
|
133
|
+
export function fastifyPlugin(admin: Pick<DbAdmin, 'fetch' | 'basePath'>) {
|
|
134
|
+
const handle = toNodeHandler(admin)
|
|
135
|
+
return async function otwDb(fastify: FastifyLike): Promise<void> {
|
|
136
|
+
fastify.removeAllContentTypeParsers()
|
|
137
|
+
fastify.addContentTypeParser('*', (_request, _payload, done) => done(null))
|
|
138
|
+
const route = async (
|
|
139
|
+
request: { raw: IncomingMessage },
|
|
140
|
+
reply: { raw: ServerResponse; hijack(): void },
|
|
141
|
+
) => {
|
|
142
|
+
reply.hijack()
|
|
143
|
+
await handle(request.raw, reply.raw)
|
|
144
|
+
}
|
|
145
|
+
fastify.all(admin.basePath || '/', route)
|
|
146
|
+
fastify.all(`${admin.basePath}/*`, route)
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** What the Koa middleware uses of Koa's context. */
|
|
151
|
+
interface KoaContext {
|
|
152
|
+
path: string
|
|
153
|
+
req: IncomingMessage
|
|
154
|
+
res: ServerResponse
|
|
155
|
+
respond?: boolean
|
|
156
|
+
request: { body?: unknown }
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Koa middleware: `app.use(koaMiddleware(dbAdmin))`. Paths outside the base path go on to the
|
|
161
|
+
* next middleware. A body a parser before it read (koa-bodyparser) is handed over.
|
|
162
|
+
*/
|
|
163
|
+
export function koaMiddleware(admin: Pick<DbAdmin, 'fetch' | 'basePath'>) {
|
|
164
|
+
const handle = toNodeHandler(admin)
|
|
165
|
+
return async (ctx: KoaContext, next: () => Promise<unknown>): Promise<unknown> => {
|
|
166
|
+
if (!within(ctx.path, admin.basePath)) return next()
|
|
167
|
+
const req = ctx.req as IncomingMessage & { body?: unknown }
|
|
168
|
+
if (req.readableEnded && req.body === undefined) req.body = ctx.request.body
|
|
169
|
+
ctx.respond = false
|
|
170
|
+
await handle(ctx.req, ctx.res)
|
|
171
|
+
}
|
|
172
|
+
}
|