@ultimabase/http 0.0.0-stage → 0.1.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.
Files changed (47) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +4 -2
  3. package/dist/address.d.ts +9 -0
  4. package/dist/address.d.ts.map +1 -0
  5. package/dist/address.js +63 -0
  6. package/dist/app.d.ts +43 -0
  7. package/dist/app.d.ts.map +1 -0
  8. package/dist/app.js +200 -0
  9. package/dist/client.d.ts +9 -0
  10. package/dist/client.d.ts.map +1 -0
  11. package/dist/client.js +31 -0
  12. package/dist/index.d.ts +39 -0
  13. package/dist/index.d.ts.map +1 -0
  14. package/dist/index.js +89 -0
  15. package/dist/internal.d.ts +5 -0
  16. package/dist/internal.d.ts.map +1 -0
  17. package/dist/internal.js +2 -0
  18. package/dist/pages.d.ts +60 -0
  19. package/dist/pages.d.ts.map +1 -0
  20. package/dist/pages.js +124 -0
  21. package/dist/request.d.ts +5 -0
  22. package/dist/request.d.ts.map +1 -0
  23. package/dist/request.js +26 -0
  24. package/dist/server.d.ts +15 -0
  25. package/dist/server.d.ts.map +1 -0
  26. package/dist/server.js +73 -0
  27. package/dist/transport.d.ts +32 -0
  28. package/dist/transport.d.ts.map +1 -0
  29. package/dist/transport.js +55 -0
  30. package/dist/upgrade.d.ts +25 -0
  31. package/dist/upgrade.d.ts.map +1 -0
  32. package/dist/upgrade.js +63 -0
  33. package/dist/validate.d.ts +44 -0
  34. package/dist/validate.d.ts.map +1 -0
  35. package/dist/validate.js +36 -0
  36. package/package.json +44 -3
  37. package/src/address.ts +74 -0
  38. package/src/app.ts +263 -0
  39. package/src/client.ts +38 -0
  40. package/src/index.ts +133 -0
  41. package/src/internal.ts +29 -0
  42. package/src/pages.ts +200 -0
  43. package/src/request.ts +40 -0
  44. package/src/server.ts +90 -0
  45. package/src/transport.ts +84 -0
  46. package/src/upgrade.ts +105 -0
  47. package/src/validate.ts +96 -0
package/dist/pages.js ADDED
@@ -0,0 +1,124 @@
1
+ import { isRow } from 'ultimabase/internal';
2
+ import { badInput } from './transport.js';
3
+ const encode = (id) => Buffer.from(id).toString('base64url');
4
+ function decode(cursor, arg) {
5
+ const id = Buffer.from(cursor, 'base64url').toString();
6
+ if (id === '' || encode(id) !== cursor) {
7
+ throw badInput(`${arg} is not a cursor this API returned.`);
8
+ }
9
+ return id;
10
+ }
11
+ /** An `Int` argument; `null` is absent, as in GraphQL. */
12
+ function integer(args, name, at) {
13
+ const value = args[name];
14
+ if (value === undefined || value === null)
15
+ return undefined;
16
+ if (typeof value === 'number' && Number.isSafeInteger(value))
17
+ return value;
18
+ throw badInput(`${at(name)} must be an integer.`);
19
+ }
20
+ /** A `String` argument; `null` is absent, as in GraphQL. */
21
+ function text(args, name, at) {
22
+ const value = args[name];
23
+ if (value === undefined || value === null)
24
+ return undefined;
25
+ if (typeof value === 'string')
26
+ return value;
27
+ throw badInput(`${at(name)} must be a string.`);
28
+ }
29
+ /** The rows asked for, within the model's limits unless Master asks. */
30
+ function size(asked, name, limits, master) {
31
+ if (asked !== undefined && asked < 0) {
32
+ throw badInput(`${name} cannot be negative.`);
33
+ }
34
+ if (master)
35
+ return asked;
36
+ if (asked !== undefined && asked > limits.maxTake) {
37
+ throw badInput(`${name} is at most ${limits.maxTake} on ${limits.model.name}.`);
38
+ }
39
+ return asked ?? limits.take;
40
+ }
41
+ /**
42
+ * One row more than asked tells whether another page follows. The cursor's
43
+ * row is included by the kernel, so `skip: 1` starts after it.
44
+ */
45
+ function relay(args, limits, master, at) {
46
+ const after = text(args, 'after', at);
47
+ const before = text(args, 'before', at);
48
+ const first = integer(args, 'first', at);
49
+ const last = integer(args, 'last', at);
50
+ const backward = last !== undefined || before !== undefined;
51
+ if (backward && (first !== undefined || after !== undefined)) {
52
+ throw badInput('Page forward with first and after, or backward with last and before, not both.');
53
+ }
54
+ const rows = backward
55
+ ? size(last, at('last'), limits, master)
56
+ : size(first, at('first'), limits, master);
57
+ const cursor = backward ? before : after;
58
+ const read = {};
59
+ if (rows !== undefined)
60
+ read['take'] = backward ? -(rows + 1) : rows + 1;
61
+ // Master's whole list, read backward from a cursor.
62
+ else if (backward)
63
+ read['take'] = -Number.MAX_SAFE_INTEGER;
64
+ if (cursor !== undefined) {
65
+ read['cursor'] = { id: decode(cursor, at(backward ? 'before' : 'after')) };
66
+ read['skip'] = 1;
67
+ }
68
+ return { read, relay: { size: rows, backward } };
69
+ }
70
+ /** `take` and `skip` for `pagination: 'list'`. */
71
+ function list(args, limits, master, at) {
72
+ const take = size(integer(args, 'take', at), at('take'), limits, master);
73
+ const skip = integer(args, 'skip', at);
74
+ const read = {
75
+ ...(take === undefined ? {} : { take }),
76
+ ...(skip === undefined ? {} : { skip }),
77
+ };
78
+ return { read, relay: undefined };
79
+ }
80
+ /** The page a list's arguments ask for. */
81
+ export const pageOf = (pagination, limits, args, master, at = (name) => name) => pagination === 'list'
82
+ ? list(args, limits, master, at)
83
+ : relay(args, limits, master, at);
84
+ /** The page arguments of each pagination. */
85
+ export const pageArgs = (pagination) => pagination === 'list'
86
+ ? ['take', 'skip']
87
+ : ['first', 'after', 'last', 'before'];
88
+ /** The rows of a Relay read, without the one read to look ahead. */
89
+ export function connection(rows, page, node) {
90
+ const more = page.size !== undefined && rows.length > page.size;
91
+ const kept = more ? (page.backward ? rows.slice(1) : rows.slice(0, -1)) : rows;
92
+ const edges = kept.map((row) => ({ cursor: encode(row.id), node: node(row) }));
93
+ return {
94
+ edges,
95
+ pageInfo: {
96
+ hasNextPage: more && !page.backward,
97
+ hasPreviousPage: more && page.backward,
98
+ startCursor: edges[0]?.cursor ?? null,
99
+ endCursor: edges.at(-1)?.cursor ?? null,
100
+ },
101
+ };
102
+ }
103
+ /** A row's relation as the kernel returned it. */
104
+ export function rowsOf(value) {
105
+ return Array.isArray(value) ? value.filter(isRow) : [];
106
+ }
107
+ export const rowOf = (value) => isRow(value) ? value : undefined;
108
+ /** `window` once a live read's `changes` are applied, in their order. */
109
+ export function applied(window, changes, kept) {
110
+ let rows = [...window];
111
+ for (const change of changes) {
112
+ if ('remove' in change) {
113
+ rows = rows.filter(({ id }) => id !== change.remove);
114
+ continue;
115
+ }
116
+ const row = kept(change.upsert);
117
+ rows = rows.filter(({ id }) => id !== row.id);
118
+ const at = change.after === null
119
+ ? 0
120
+ : rows.findIndex(({ id }) => id === change.after) + 1;
121
+ rows.splice(at, 0, row);
122
+ }
123
+ return rows;
124
+ }
@@ -0,0 +1,5 @@
1
+ import type { Context } from 'hono';
2
+ import type { Caller } from 'ultimabase';
3
+ import type { HttpEnv } from './app.ts';
4
+ export declare function hold(c: Context<HttpEnv>, caller: Caller, address: string): void;
5
+ //# sourceMappingURL=request.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"request.d.ts","sourceRoot":"","sources":["../src/request.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AAEnC,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,YAAY,CAAA;AACxC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,UAAU,CAAA;AAsBvC,wBAAgB,IAAI,CACnB,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,EACnB,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,MAAM,GACb,IAAI,CAQN"}
@@ -0,0 +1,26 @@
1
+ import { HTTPException } from 'hono/http-exception';
2
+ /** `c.req[method]`, its parsing failure, `parsing`, a 400. */
3
+ function malformed(c, method, parsing, message) {
4
+ const read = c.req[method].bind(c.req);
5
+ Object.defineProperty(c.req, method, {
6
+ value: async (...args) => {
7
+ try {
8
+ return await read(...args);
9
+ }
10
+ catch (error) {
11
+ if (!(error instanceof parsing))
12
+ throw error;
13
+ throw new HTTPException(400, { message, cause: error });
14
+ }
15
+ },
16
+ });
17
+ }
18
+ export function hold(c, caller, address) {
19
+ c.set('caller', caller);
20
+ c.set('address', address);
21
+ // Only parsing the body throws these here, not the server's code.
22
+ malformed(c, 'json', SyntaxError, 'Malformed JSON in request body');
23
+ const form = 'Malformed form data in request body';
24
+ malformed(c, 'formData', TypeError, form);
25
+ malformed(c, 'parseBody', TypeError, form);
26
+ }
@@ -0,0 +1,15 @@
1
+ import type { Server } from 'node:http';
2
+ import type { Duplex } from 'node:stream';
3
+ import { getRequestListener } from '@hono/node-server';
4
+ import type { Logger } from 'ultimabase';
5
+ /** The `port` option, then `PORT`, then 3000. */
6
+ export declare function portOf(option: number | undefined): number;
7
+ export declare function listening(server: Server, port: number): Promise<number>;
8
+ /** A Node server for `fetch`, Hono's handler. */
9
+ export declare function serverOf(fetch: Parameters<typeof getRequestListener>[0]): Server;
10
+ /**
11
+ * Stops accepting connections, then waits for running requests and the
12
+ * sockets plugins took (D-59), 10 seconds at most (D-106).
13
+ */
14
+ export declare function closed(server: Server, logger: Logger, taken: ReadonlySet<Duplex>): Promise<void>;
15
+ //# sourceMappingURL=server.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,WAAW,CAAA;AAEvC,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAA;AACtD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,YAAY,CAAA;AAGxC,iDAAiD;AACjD,wBAAgB,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAWzD;AAED,wBAAsB,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAqB7E;AAED,iDAAiD;AACjD,wBAAgB,QAAQ,CACvB,KAAK,EAAE,UAAU,CAAC,OAAO,kBAAkB,CAAC,CAAC,CAAC,CAAC,GAC7C,MAAM,CAWR;AAKD;;;GAGG;AACH,wBAAsB,MAAM,CAC3B,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,WAAW,CAAC,MAAM,CAAC,GACxB,OAAO,CAAC,IAAI,CAAC,CAiBf"}
package/dist/server.js ADDED
@@ -0,0 +1,73 @@
1
+ import { createServer } from 'node:http';
2
+ import { getRequestListener } from '@hono/node-server';
3
+ import { Refused } from 'ultimabase';
4
+ /** The `port` option, then `PORT`, then 3000. */
5
+ export function portOf(option) {
6
+ const given = option ?? process.env['PORT'];
7
+ if (given === undefined || given === '')
8
+ return 3000;
9
+ // Digits only: `Number` would also read ' ', '0x1F90' or '1e3'.
10
+ const port = typeof given === 'number' || /^\d+$/.test(given)
11
+ ? Number(given)
12
+ : Number.NaN;
13
+ if (Number.isInteger(port) && port >= 0 && port <= 65_535)
14
+ return port;
15
+ const name = option === undefined ? 'PORT' : 'port';
16
+ throw new Refused(`${name} is ${given}, not a port between 0 and 65535.`);
17
+ }
18
+ export async function listening(server, port) {
19
+ await new Promise((done, fail) => {
20
+ const refused = (error) => {
21
+ const code = Reflect.get(error, 'code');
22
+ fail(code === 'EADDRINUSE'
23
+ ? new Error(`Port ${port} is in use: stop the process that holds it, or set PORT.`, { cause: error })
24
+ : error);
25
+ };
26
+ server.once('error', refused);
27
+ server.listen(port, () => {
28
+ server.off('error', refused);
29
+ done();
30
+ });
31
+ });
32
+ const address = server.address();
33
+ return typeof address === 'object' && address !== null ? address.port : port;
34
+ }
35
+ /** A Node server for `fetch`, Hono's handler. */
36
+ export function serverOf(fetch) {
37
+ const listener = getRequestListener(fetch);
38
+ const server = createServer((request, response) => {
39
+ // A request running when `stop` began leaves its connection idle after
40
+ // its response: close it, rather than wait for the client to.
41
+ response.once('finish', () => {
42
+ if (!server.listening)
43
+ server.closeIdleConnections();
44
+ });
45
+ void listener(request, response);
46
+ });
47
+ return server;
48
+ }
49
+ /** How long `stop` waits for running requests: a stream never ends. */
50
+ const grace = 10_000;
51
+ /**
52
+ * Stops accepting connections, then waits for running requests and the
53
+ * sockets plugins took (D-59), 10 seconds at most (D-106).
54
+ */
55
+ export async function closed(server, logger, taken) {
56
+ let cutting;
57
+ await new Promise((done, fail) => {
58
+ server.close((error) => {
59
+ clearTimeout(cutting);
60
+ if (error === undefined)
61
+ done();
62
+ else
63
+ fail(error);
64
+ });
65
+ server.closeIdleConnections();
66
+ cutting = setTimeout(() => {
67
+ logger.warn(`Stopped ${grace / 1000} s after stop began: closed the requests still running.`);
68
+ server.closeAllConnections();
69
+ for (const socket of taken)
70
+ socket.destroy();
71
+ }, grace);
72
+ });
73
+ }
@@ -0,0 +1,32 @@
1
+ import type { ExposedVirtual, SchemaField, SchemaModel } from 'ultimabase';
2
+ /** An argument, a parameter or a body of the client's that the API refuses. */
3
+ export declare const badInput: (message: string, cause?: unknown) => Error;
4
+ /**
5
+ * Runs a kernel query. The arguments come from the client's request, so
6
+ * one the kernel refuses is the client's error, not the server's.
7
+ */
8
+ export declare function run<T>(query: () => Promise<T>): Promise<T>;
9
+ /** `post` → `posts`, `category` → `categories`, `box` → `boxes`. */
10
+ export declare function plural(name: string): string;
11
+ /** A model a transport serves, with its fields' read rules. */
12
+ export type Served = {
13
+ readonly model: SchemaModel;
14
+ readonly exposed: {
15
+ readonly readRules: {
16
+ readonly [field: string]: 'private' | 'rule';
17
+ };
18
+ readonly virtuals: readonly ExposedVirtual[];
19
+ };
20
+ };
21
+ /** The fields a client reads: no `private` one, for Master too (D-44). */
22
+ export declare const readable: (served: Served) => readonly SchemaField[];
23
+ /** The virtual fields a client reads, as `readable` (D-151). */
24
+ export declare const readableVirtuals: (served: Served) => readonly ExposedVirtual[];
25
+ /** A JSON Schema, or one of its nodes. */
26
+ export type Node = {
27
+ readonly [key: string]: unknown;
28
+ };
29
+ export declare const isNode: (value: unknown) => value is Node;
30
+ /** A schema's JSON Schema, or startup stops naming `where` (D-45). */
31
+ export declare function jsonSchemaOf(schema: object, side: 'input' | 'output', where: string): Node;
32
+ //# sourceMappingURL=transport.d.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,MAAM,GACX,IAAI,CAiBN"}
@@ -0,0 +1,55 @@
1
+ import { InvalidQuery, PublicError, Refused } from 'ultimabase';
2
+ /** An argument, a parameter or a body of the client's that the API refuses. */
3
+ export const badInput = (message, cause) => new PublicError('BAD_USER_INPUT', message, { cause });
4
+ /**
5
+ * Runs a kernel query. The arguments come from the client's request, so
6
+ * one the kernel refuses is the client's error, not the server's.
7
+ */
8
+ export async function run(query) {
9
+ try {
10
+ return await query();
11
+ }
12
+ catch (error) {
13
+ if (error instanceof InvalidQuery) {
14
+ throw new PublicError('BAD_USER_INPUT', error.message, {
15
+ details: { path: error.path },
16
+ cause: error,
17
+ });
18
+ }
19
+ throw error;
20
+ }
21
+ }
22
+ /** `post` → `posts`, `category` → `categories`, `box` → `boxes`. */
23
+ export function plural(name) {
24
+ if (/[^aeiou]y$/i.test(name))
25
+ return `${name.slice(0, -1)}ies`;
26
+ if (/(?:s|x|z|ch|sh)$/i.test(name))
27
+ return `${name}es`;
28
+ return `${name}s`;
29
+ }
30
+ /** The fields a client reads: no `private` one, for Master too (D-44). */
31
+ export const readable = (served) => served.model.fields.filter((field) => served.exposed.readRules[field.name] !== 'private');
32
+ /** The virtual fields a client reads, as `readable` (D-151). */
33
+ export const readableVirtuals = (served) => served.exposed.virtuals.filter((virtual) => served.exposed.readRules[virtual.name] !== 'private');
34
+ export const isNode = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
35
+ /** A schema's JSON Schema, or startup stops naming `where` (D-45). */
36
+ export function jsonSchemaOf(schema, side, where) {
37
+ const standard = Reflect.get(schema, '~standard');
38
+ const exporter = isNode(standard) ? standard['jsonSchema'] : undefined;
39
+ const exported = isNode(exporter) ? exporter[side] : undefined;
40
+ if (typeof exported !== 'function') {
41
+ throw new Refused(`${where} has no standard JSON Schema export.`);
42
+ }
43
+ try {
44
+ const node = Reflect.apply(exported, exporter, [
45
+ { target: 'draft-2020-12' },
46
+ ]);
47
+ if (isNode(node))
48
+ return node;
49
+ }
50
+ catch (error) {
51
+ const reason = error instanceof Error ? error.message : String(error);
52
+ throw new Refused(`${where}: ${reason}.`, { cause: error });
53
+ }
54
+ throw new Refused(`${where}'s JSON Schema is not an object.`);
55
+ }
@@ -0,0 +1,25 @@
1
+ import type { IncomingMessage, Server } from 'node:http';
2
+ import type { Duplex } from 'node:stream';
3
+ import type { Logger } from 'ultimabase';
4
+ /**
5
+ * An upgrade a plugin takes: Node's request, its socket and first bytes, as
6
+ * `ws`'s `handleUpgrade` reads them, the request `identify` reads and the
7
+ * client's address, as `proxies` reads it (D-116).
8
+ */
9
+ export interface Upgrade {
10
+ readonly request: Request;
11
+ readonly address: string;
12
+ readonly incoming: IncomingMessage;
13
+ readonly socket: Duplex;
14
+ readonly head: Buffer;
15
+ }
16
+ /** Takes an upgrade on its path; the socket is the plugin's from then on. */
17
+ export type Accept = (upgrade: Upgrade) => void;
18
+ /**
19
+ * Hands each upgrade to its path's plugin, past the origin check; returns
20
+ * the sockets taken and still open, which `stop` closes at its end.
21
+ */
22
+ export declare function upgrading(server: Server, accepts: ReadonlyMap<string, Accept>, allows: (origin: string) => boolean, addressOf: (env: {
23
+ readonly incoming: IncomingMessage;
24
+ }) => string, logger: Logger): ReadonlySet<Duplex>;
25
+ //# sourceMappingURL=upgrade.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upgrade.d.ts","sourceRoot":"","sources":["../src/upgrade.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,WAAW,CAAA;AAExD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACzC,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,YAAY,CAAA;AAExC;;;;GAIG;AACH,MAAM,WAAW,OAAO;IACvB,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAA;IACzB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;IACxB,QAAQ,CAAC,QAAQ,EAAE,eAAe,CAAA;IAClC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;CACrB;AAED,6EAA6E;AAC7E,MAAM,MAAM,MAAM,GAAG,CAAC,OAAO,EAAE,OAAO,KAAK,IAAI,CAAA;AAsC/C;;;GAGG;AACH,wBAAgB,SAAS,CACxB,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,EACpC,MAAM,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,EACnC,SAAS,EAAE,CAAC,GAAG,EAAE;IAAE,QAAQ,CAAC,QAAQ,EAAE,eAAe,CAAA;CAAE,KAAK,MAAM,EAClE,MAAM,EAAE,MAAM,GACZ,WAAW,CAAC,MAAM,CAAC,CAkCrB"}
@@ -0,0 +1,63 @@
1
+ import { STATUS_CODES } from 'node:http';
2
+ /** Answers `status` with an error as D-72 sends it, then closes the socket. */
3
+ function refuse(socket, status, code, message) {
4
+ const body = JSON.stringify({ code, message });
5
+ socket.end([
6
+ `HTTP/1.1 ${status} ${STATUS_CODES[status] ?? ''}`,
7
+ 'connection: close',
8
+ 'content-type: application/json',
9
+ `content-length: ${Buffer.byteLength(body)}`,
10
+ '',
11
+ body,
12
+ ].join('\r\n'));
13
+ }
14
+ /** The request `incoming` is, without a body; `undefined` for no valid URL. */
15
+ function requestOf(incoming) {
16
+ const { host } = incoming.headers;
17
+ const target = incoming.url ?? '';
18
+ const url = `http://${host ?? ''}${target}`;
19
+ if (host === undefined || !target.startsWith('/') || !URL.canParse(url)) {
20
+ return undefined;
21
+ }
22
+ const headers = new Headers();
23
+ const raw = incoming.rawHeaders;
24
+ for (let index = 0; index + 1 < raw.length; index += 2) {
25
+ headers.append(raw[index] ?? '', raw[index + 1] ?? '');
26
+ }
27
+ return new Request(url, { headers });
28
+ }
29
+ /**
30
+ * Hands each upgrade to its path's plugin, past the origin check; returns
31
+ * the sockets taken and still open, which `stop` closes at its end.
32
+ */
33
+ export function upgrading(server, accepts, allows, addressOf, logger) {
34
+ const open = new Set();
35
+ server.on('upgrade', (incoming, socket, head) => {
36
+ // A client that leaves mid-answer must not stop the server.
37
+ socket.on('error', () => socket.destroy());
38
+ const request = requestOf(incoming);
39
+ if (request === undefined) {
40
+ return refuse(socket, 400, 'BAD_REQUEST', 'The upgrade has no URL.');
41
+ }
42
+ const { origin, pathname } = new URL(request.url);
43
+ const accept = accepts.get(pathname);
44
+ if (accept === undefined) {
45
+ return refuse(socket, 404, 'NOT_FOUND', `No upgrade at ${pathname}.`);
46
+ }
47
+ const from = incoming.headers.origin;
48
+ if (from !== undefined && from !== origin && !allows(from)) {
49
+ return refuse(socket, 403, 'ACCESS_DENIED', 'A WebSocket from another origin is refused.');
50
+ }
51
+ open.add(socket);
52
+ socket.once('close', () => open.delete(socket));
53
+ try {
54
+ const address = addressOf({ incoming });
55
+ accept({ request, address, incoming, socket, head });
56
+ }
57
+ catch (error) {
58
+ logger.error({ err: error }, 'An upgrade failed.');
59
+ refuse(socket, 500, 'INTERNAL', 'Internal error.');
60
+ }
61
+ });
62
+ return open;
63
+ }
@@ -0,0 +1,44 @@
1
+ import type { Env, MiddlewareHandler, ValidationTargets } from 'hono';
2
+ type Segment = PropertyKey | {
3
+ readonly key: PropertyKey;
4
+ };
5
+ /**
6
+ * Standard Schema (standardschema.dev), the part read here. Its
7
+ * specification asks for the interface to be copied, not imported.
8
+ */
9
+ export interface StandardSchema {
10
+ readonly '~standard': {
11
+ readonly validate: (value: unknown) => Result | Promise<Result>;
12
+ readonly types?: {
13
+ readonly input: unknown;
14
+ } | undefined;
15
+ };
16
+ }
17
+ type Result = {
18
+ readonly value: unknown;
19
+ readonly issues?: undefined;
20
+ } | {
21
+ readonly issues: readonly {
22
+ readonly message: string;
23
+ readonly path?: readonly Segment[] | undefined;
24
+ }[];
25
+ };
26
+ /** What the schema returns for a value it accepts. */
27
+ type Output<S extends StandardSchema> = Extract<Awaited<ReturnType<S['~standard']['validate']>>, {
28
+ readonly value: unknown;
29
+ }>['value'];
30
+ /** What the schema takes, `unknown` when it declares no types. */
31
+ type Input<S extends StandardSchema> = NonNullable<S['~standard']['types']>['input'];
32
+ /** What a route reads with `c.req.valid(target)`, and a client sends. */
33
+ type Validated<T extends keyof ValidationTargets, S extends StandardSchema> = {
34
+ readonly in: {
35
+ readonly [K in T]: K extends 'json' ? Input<S> : NonNullable<Input<S>>;
36
+ };
37
+ readonly out: {
38
+ readonly [K in T]: Output<S>;
39
+ };
40
+ };
41
+ /** Refuses the request with the issues the schema reports, as the kernel does. */
42
+ export declare const validate: <T extends keyof ValidationTargets, S extends StandardSchema>(target: T, schema: S) => MiddlewareHandler<Env, string, Validated<T, S>>;
43
+ export {};
44
+ //# sourceMappingURL=validate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validate.d.ts","sourceRoot":"","sources":["../src/validate.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,GAAG,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAA;AAMrE,KAAK,OAAO,GAAG,WAAW,GAAG;IAAE,QAAQ,CAAC,GAAG,EAAE,WAAW,CAAA;CAAE,CAAA;AAE1D;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC9B,QAAQ,CAAC,WAAW,EAAE;QACrB,QAAQ,CAAC,QAAQ,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAA;QAC/D,QAAQ,CAAC,KAAK,CAAC,EAAE;YAAE,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAA;SAAE,GAAG,SAAS,CAAA;KACxD,CAAA;CACD;AACD,KAAK,MAAM,GACR;IAAE,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC;IAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,SAAS,CAAA;CAAE,GACxD;IACA,QAAQ,CAAC,MAAM,EAAE,SAAS;QACzB,QAAQ,CAAC,OAAO,EA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's own test: a body it does not take as JSON, it validates as `{}`.
5
+ const json = /^application\/([a-z-.]+\+)?json(;\s*[a-zA-Z0-9-]+=([^;]+))*$/i;
6
+ const keyOf = (segment) => {
7
+ const key = typeof segment === 'object' ? segment.key : segment;
8
+ return typeof key === 'symbol' ? String(key) : key;
9
+ };
10
+ /** Refuses the request with the issues the schema reports, as the kernel does. */
11
+ export const validate = (target, schema) => {
12
+ const check = async (value) => {
13
+ const result = await schema['~standard'].validate(value);
14
+ if (result.issues === undefined)
15
+ return result.value;
16
+ const issues = result.issues.map((issue) => ({
17
+ path: (issue.path ?? []).map(keyOf),
18
+ message: issue.message,
19
+ }));
20
+ throw new PublicError('VALIDATION_FAILED', 'Invalid data.', {
21
+ details: { issues },
22
+ });
23
+ };
24
+ // Hono infers the value from `check`; the schema gives its type.
25
+ const validating = validator(target, check);
26
+ if (target !== 'json')
27
+ return validating;
28
+ return async (c, next) => {
29
+ if (!json.test(c.req.header('content-type') ?? '')) {
30
+ throw new HTTPException(415, {
31
+ message: 'The body is not JSON: send content-type: application/json.',
32
+ });
33
+ }
34
+ return validating(c, next);
35
+ };
36
+ };
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "@ultimabase/http",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "An HTTP server for UltimaBase: Hono routes that read the caller, CORS and a body limit.",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "homepage": "https://ultimabase.dev/docs/http",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/MrEkinox/ultimabase.git",
11
+ "directory": "packages/http"
12
+ },
13
+ "engines": {
14
+ "node": ">=24.7.0"
15
+ },
16
+ "exports": {
17
+ ".": "./dist/index.js",
18
+ "./internal": "./dist/internal.js"
19
+ },
20
+ "files": [
21
+ "dist",
22
+ "src",
23
+ "!src/**/*.test.ts",
24
+ "!src/test"
25
+ ],
26
+ "scripts": {
27
+ "prepack": "rm -rf dist && yarn run -T tsc --project tsconfig.build.json"
28
+ },
29
+ "publishConfig": {
30
+ "exports": {
31
+ ".": "./dist/index.js",
32
+ "./internal": "./dist/internal.js"
33
+ }
34
+ },
35
+ "dependencies": {
36
+ "@hono/node-server": "2.1.3",
37
+ "hono": "4.13.13"
38
+ },
39
+ "peerDependencies": {
40
+ "ultimabase": "^0.1.1"
41
+ },
42
+ "devDependencies": {
43
+ "ultimabase": "0.1.1",
44
+ "vite": "8.3.4",
45
+ "vitest": "5.0.5"
46
+ }
6
47
  }
package/src/address.ts ADDED
@@ -0,0 +1,74 @@
1
+ // A client's address (D-113, D-116): the connection's, or the one the
2
+ // proxies in front of the server forwarded.
3
+ import { IncomingMessage } from 'node:http'
4
+ import { BlockList, isIP } from 'node:net'
5
+ import type { Logger } from 'ultimabase'
6
+ import { Refused } from 'ultimabase'
7
+
8
+ // Where a proxy in front of the server connects from.
9
+ const nearby = new BlockList()
10
+ for (const [network, prefix] of [
11
+ ['127.0.0.0', 8],
12
+ ['10.0.0.0', 8],
13
+ ['172.16.0.0', 12],
14
+ ['192.168.0.0', 16],
15
+ ['100.64.0.0', 10],
16
+ ] as const) {
17
+ nearby.addSubnet(network, prefix, 'ipv4')
18
+ }
19
+ for (const [network, prefix] of [
20
+ ['::1', 128],
21
+ ['fc00::', 7],
22
+ ['fe80::', 10],
23
+ ] as const) {
24
+ nearby.addSubnet(network, prefix, 'ipv6')
25
+ }
26
+
27
+ const isNearby = (address: string): boolean =>
28
+ nearby.check(address, isIP(address) === 4 ? 'ipv4' : 'ipv6')
29
+
30
+ /** The `proxies` option, a whole number; 0 by default. */
31
+ export function proxiesOf(option: number | undefined): number {
32
+ const proxies = option ?? 0
33
+ if (Number.isInteger(proxies) && proxies >= 0) return proxies
34
+ throw new Refused(
35
+ `proxies is ${proxies}, not a whole number of proxies in front of the server.`,
36
+ )
37
+ }
38
+
39
+ /**
40
+ * Reads the address of the Node connection a request's `env` holds, `''`
41
+ * without one, or the one `proxies` proxies forwarded.
42
+ */
43
+ export function addresses(
44
+ proxies: number,
45
+ logger: Logger,
46
+ ): (env: unknown) => string {
47
+ let warned = false
48
+ return (env) => {
49
+ const incoming: unknown =
50
+ typeof env === 'object' && env !== null
51
+ ? Reflect.get(env, 'incoming')
52
+ : undefined
53
+ if (!(incoming instanceof IncomingMessage)) return ''
54
+ const connection = incoming.socket.remoteAddress ?? ''
55
+ const forwarded = incoming.headersDistinct['x-forwarded-for']
56
+ if (forwarded === undefined) return connection
57
+ if (proxies === 0) {
58
+ if (!warned && isNearby(connection)) {
59
+ warned = true
60
+ logger.warn(
61
+ `A request came through a proxy (X-Forwarded-For) but httpPlugin({ proxies }) is not set: every client counts as ${connection}. Set it to the number of proxies in front of the server.`,
62
+ )
63
+ }
64
+ return connection
65
+ }
66
+ // Each proxy appended the address it saw: the client's is n from the
67
+ // right. With fewer, the client went around a proxy and wrote them.
68
+ const entries = forwarded
69
+ .flatMap((header) => header.split(','))
70
+ .map((entry) => entry.trim())
71
+ const entry = entries.at(-proxies) ?? ''
72
+ return entries.length < proxies || isIP(entry) === 0 ? connection : entry
73
+ }
74
+ }