@plitzi/sdk-kernel 0.0.0-stage → 0.39.2
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/CHANGELOG.md +10 -0
- package/README.md +80 -2
- package/dist/build/esbuild.d.ts +16 -0
- package/dist/build/index.d.ts +1 -0
- package/dist/build/index.mjs +35 -0
- package/dist/cache/CompressedFileCache.d.ts +18 -0
- package/dist/cache/TtlCache.d.ts +65 -0
- package/dist/cache/index.d.ts +3 -0
- package/dist/cache/index.mjs +1 -0
- package/dist/chunks/TtlCache-J_jG9oL9.mjs +200 -0
- package/dist/chunks/channel-DnVf7PJB.mjs +190 -0
- package/dist/chunks/csrf-BLWcaYOV.mjs +295 -0
- package/dist/chunks/link-C9wyDS9H.mjs +124 -0
- package/dist/chunks/query-DGbrN3mN.mjs +20 -0
- package/dist/chunks/scopes-Co6ZjhAm.mjs +46 -0
- package/dist/chunks/serverLog-BKaKjjc4.mjs +137 -0
- package/dist/chunks/session-B-dTEjeG.mjs +253 -0
- package/dist/chunks/sessionActivity-Ch7xuQ_o.mjs +43 -0
- package/dist/chunks/spaceDeployment-J2IMLfij.mjs +76 -0
- package/dist/chunks/stage-y6deE9LJ.mjs +345 -0
- package/dist/chunks/supervisor-Dh34v1vq.mjs +117 -0
- package/dist/chunks/tail-D-USrZIR.mjs +55 -0
- package/dist/chunks/tokens-CBd5tXut.mjs +262 -0
- package/dist/data/index.d.ts +2 -0
- package/dist/data/index.mjs +68 -0
- package/dist/data/projectData.d.ts +21 -0
- package/dist/deployment/hostDeployment.d.ts +8 -0
- package/dist/deployment/index.d.ts +3 -0
- package/dist/deployment/index.mjs +19 -0
- package/dist/deployment/spaceDeployment.d.ts +11 -0
- package/dist/engine/index.d.ts +2 -0
- package/dist/engine/index.mjs +1 -0
- package/dist/engine/page.d.ts +49 -0
- package/dist/engine/rsc.d.ts +32 -0
- package/dist/files/atomicFile.d.ts +10 -0
- package/dist/files/index.d.ts +1 -0
- package/dist/files/index.mjs +32 -0
- package/dist/http/bearer.d.ts +5 -0
- package/dist/http/buildResponseHelpers.d.ts +23 -0
- package/dist/http/closeOnSignals.d.ts +28 -0
- package/dist/http/compress.d.ts +20 -0
- package/dist/http/dispatcher.d.ts +15 -0
- package/dist/http/drain.d.ts +18 -0
- package/dist/http/fleet/channel.d.ts +103 -0
- package/dist/http/fleet/link.d.ts +28 -0
- package/dist/http/fleet/role.d.ts +46 -0
- package/dist/http/fleet/supervisor.d.ts +29 -0
- package/dist/http/freePort.d.ts +24 -0
- package/dist/http/health.d.ts +21 -0
- package/dist/http/index.d.ts +48 -0
- package/dist/http/index.mjs +1313 -0
- package/dist/http/middlewares/auth.d.ts +2 -0
- package/dist/http/middlewares/basicAuth.d.ts +6 -0
- package/dist/http/mimeTypes.d.ts +13 -0
- package/dist/http/navigation.d.ts +14 -0
- package/dist/http/onAbort.d.ts +12 -0
- package/dist/http/probes.d.ts +4 -0
- package/dist/http/requestParser.d.ts +22 -0
- package/dist/http/runMiddlewares.d.ts +6 -0
- package/dist/http/securityHeaders.d.ts +18 -0
- package/dist/http/server.d.ts +39 -0
- package/dist/http/socketResponse.d.ts +18 -0
- package/dist/http/sse.d.ts +26 -0
- package/dist/http/stages/crossSiteWrites.d.ts +24 -0
- package/dist/http/stages/health.d.ts +11 -0
- package/dist/http/stages/middlewares.d.ts +3 -0
- package/dist/http/stages/static.d.ts +4 -0
- package/dist/http/staticFiles.d.ts +3 -0
- package/dist/http/stopping.d.ts +11 -0
- package/dist/http/transports.d.ts +31 -0
- package/dist/http/types.d.ts +29 -0
- package/dist/http/unusedPort.d.ts +10 -0
- package/dist/http/webExchange.d.ts +18 -0
- package/dist/http/wsFrame.d.ts +3 -0
- package/dist/identity/accounts.d.ts +278 -0
- package/dist/identity/authorize.d.ts +96 -0
- package/dist/identity/credentials.d.ts +40 -0
- package/dist/identity/csrf.d.ts +139 -0
- package/dist/identity/debugAuthorization.d.ts +24 -0
- package/dist/identity/domains.d.ts +41 -0
- package/dist/identity/identity.d.ts +119 -0
- package/dist/identity/index.d.ts +21 -0
- package/dist/identity/index.mjs +731 -0
- package/dist/identity/passwords.d.ts +15 -0
- package/dist/identity/previewToken.d.ts +21 -0
- package/dist/identity/requestIdentity.d.ts +14 -0
- package/dist/identity/scopes.d.ts +56 -0
- package/dist/identity/session.d.ts +185 -0
- package/dist/identity/sessionActivity.d.ts +11 -0
- package/dist/identity/spaceTokens.d.ts +174 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.mjs +1 -0
- package/dist/log/index.d.ts +3 -0
- package/dist/log/index.mjs +3 -0
- package/dist/log/serverLog.d.ts +49 -0
- package/dist/log/tail.d.ts +43 -0
- package/dist/mysql/accounts.d.ts +4 -0
- package/dist/mysql/admin.d.ts +58 -0
- package/dist/mysql/config.d.ts +82 -0
- package/dist/mysql/identities.d.ts +35 -0
- package/dist/mysql/index.d.ts +7 -0
- package/dist/mysql/index.mjs +1203 -0
- package/dist/mysql/pool.d.ts +3 -0
- package/dist/mysql/query.d.ts +12 -0
- package/dist/mysql/schema.d.ts +43 -0
- package/dist/mysql/sessions.d.ts +23 -0
- package/dist/mysql/spaceTokens.d.ts +11 -0
- package/dist/mysql/store.d.ts +66 -0
- package/dist/outbound/index.d.ts +4 -0
- package/dist/outbound/index.mjs +314 -0
- package/dist/outbound/inside.d.ts +36 -0
- package/dist/outbound/outboundGuard.d.ts +69 -0
- package/dist/pubsub/index.d.ts +3 -0
- package/dist/pubsub/index.mjs +76 -0
- package/dist/pubsub/memoryPubSub.d.ts +10 -0
- package/dist/pubsub/redisPubSub.d.ts +24 -0
- package/dist/stats/index.d.ts +9 -0
- package/dist/stats/index.mjs +228 -0
- package/dist/stats/load.d.ts +31 -0
- package/dist/stats/memory.d.ts +20 -0
- package/dist/stats/pools.d.ts +15 -0
- package/dist/stats/recorder.d.ts +34 -0
- package/dist/stats/stage.d.ts +15 -0
- package/dist/stats/types.d.ts +309 -0
- package/dist/testing/certificates.d.ts +21 -0
- package/dist/testing/fleet.d.ts +28 -0
- package/dist/testing/goneRuns.d.ts +5 -0
- package/dist/testing/index.d.ts +5 -0
- package/dist/testing/index.mjs +270 -0
- package/dist/testing/keys.d.ts +2 -0
- package/dist/testing/runNames.d.ts +10 -0
- package/dist/tokens/index.d.ts +2 -0
- package/dist/tokens/index.mjs +1 -0
- package/dist/tokens/tokens.d.ts +190 -0
- package/dist/types/adapters.d.ts +388 -0
- package/dist/types/config.d.ts +240 -0
- package/dist/types/index.d.ts +5 -0
- package/dist/types/index.mjs +1 -0
- package/dist/types/log.d.ts +119 -0
- package/dist/types/oauth.d.ts +246 -0
- package/dist/types/pipeline.d.ts +239 -0
- package/package.json +67 -3
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { Pool, PoolConnection, ResultSetHeader } from 'mysql2/promise';
|
|
2
|
+
export type Queryable = Pool | PoolConnection;
|
|
3
|
+
/**
|
|
4
|
+
* The driver boundary, in one place.
|
|
5
|
+
*
|
|
6
|
+
* A row arrives as `RowDataPacket` — an index signature over `unknown`, which is all the driver can honestly say
|
|
7
|
+
* about a result set it has not been told the shape of. Naming that shape is a cast whichever way it is written, so
|
|
8
|
+
* it is written once, here, rather than at each of the thirty call sites that would otherwise each carry one.
|
|
9
|
+
*/
|
|
10
|
+
export declare const selectRows: <T>(db: Queryable, sql: string, params?: unknown[]) => Promise<T[]>;
|
|
11
|
+
export declare const selectOne: <T>(db: Queryable, sql: string, params?: unknown[]) => Promise<T | undefined>;
|
|
12
|
+
export declare const execute: (db: Queryable, sql: string, params?: unknown[]) => Promise<ResultSetHeader>;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { Tables } from './config';
|
|
2
|
+
import { Pool } from 'mysql2/promise';
|
|
3
|
+
/** Adds a column unless it is already there. `definition` is everything after the column name. */
|
|
4
|
+
export declare const addColumn: (table: string, column: string, definition: string) => string[];
|
|
5
|
+
/** Removes a column if it is there. Data goes with it — a step that does this is not reversible. */
|
|
6
|
+
export declare const dropColumn: (table: string, column: string) => string[];
|
|
7
|
+
/** Adds an index unless one of that name exists. `definition` is the parenthesised column list. */
|
|
8
|
+
export declare const addIndex: (table: string, index: string, definition: string) => string[];
|
|
9
|
+
export declare const SCHEMA_VERSION: number;
|
|
10
|
+
/**
|
|
11
|
+
* Every statement this schema is made of, in order — for a deployment that runs `autoMigrate: false` and applies
|
|
12
|
+
* DDL through its own migration tool, which is the normal arrangement anywhere the application's database user is
|
|
13
|
+
* not allowed to alter tables.
|
|
14
|
+
*/
|
|
15
|
+
export declare const schemaStatements: (tables: Tables, fromVersion?: number) => string[];
|
|
16
|
+
/**
|
|
17
|
+
* Brings the schema up to date, once.
|
|
18
|
+
*
|
|
19
|
+
* The advisory lock is not decoration: an all-in-one deployment starts several roles against one database at the
|
|
20
|
+
* same moment, and without it they race to create the same tables and to bump the same version row. `IF NOT EXISTS`
|
|
21
|
+
* makes the statements survive that; the version bump would not.
|
|
22
|
+
*/
|
|
23
|
+
export declare const migrate: (pool: Pool, tables: Tables, options: {
|
|
24
|
+
prefix: string;
|
|
25
|
+
adoptExisting?: boolean;
|
|
26
|
+
log?: (message: string) => void;
|
|
27
|
+
}) => Promise<number>;
|
|
28
|
+
/**
|
|
29
|
+
* Removes this schema and nothing else.
|
|
30
|
+
*
|
|
31
|
+
* For a deployment that pointed the store at a database it shares with other things and has now stopped using
|
|
32
|
+
* `@plitzi/sdk-server` — dropping the database would take the rest of their application with it, and working out
|
|
33
|
+
* which nine tables were ours is not something anybody should have to do by hand at that moment.
|
|
34
|
+
*
|
|
35
|
+
* It drops **only** the names this schema owns, children first so the foreign keys allow it, and it refuses to
|
|
36
|
+
* touch a database it was never migrated into: without that check, a typo in `tablePrefix` turns this into a tool
|
|
37
|
+
* that deletes somebody else's `role` table.
|
|
38
|
+
*/
|
|
39
|
+
export declare const dropSchema: (pool: Pool, tables: Tables, options: {
|
|
40
|
+
prefix: string;
|
|
41
|
+
force?: boolean;
|
|
42
|
+
log?: (message: string) => void;
|
|
43
|
+
}) => Promise<string[]>;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { Tables } from './config';
|
|
2
|
+
import { Queryable } from './query';
|
|
3
|
+
import { SessionSummary } from '../identity';
|
|
4
|
+
/**
|
|
5
|
+
* The sessions of one account, as a thing that can be looked at and taken away one at a time.
|
|
6
|
+
*
|
|
7
|
+
* This is what a `session` table buys over a token pair on the account row, and it is the whole reason to pay for
|
|
8
|
+
* it: somebody who left themselves signed in on a machine they no longer have can end that session and keep the
|
|
9
|
+
* ones they are using. Revoking everything is `clearSession({ userId })` and is a blunter instrument.
|
|
10
|
+
*/
|
|
11
|
+
export declare const createSessionStore: (db: Queryable, t: Tables) => {
|
|
12
|
+
list: (accountId: number, currentToken?: string) => Promise<SessionSummary[]>;
|
|
13
|
+
/** Scoped by account as well as id, or one account could end another's session by guessing a number. */
|
|
14
|
+
revoke: (accountId: number, sessionId: number) => Promise<boolean>;
|
|
15
|
+
/** "Sign out everywhere else" — the one thing to do from a device you still trust after losing one you do not. */
|
|
16
|
+
revokeOthers: (accountId: number, currentToken: string) => Promise<number>;
|
|
17
|
+
/**
|
|
18
|
+
* Delete what has aged out. Nothing depends on this for correctness — an expired session is refused by its
|
|
19
|
+
* expiry, not by its absence — so it is housekeeping a deployment schedules, not a step in any request.
|
|
20
|
+
*/
|
|
21
|
+
purgeExpired: () => Promise<number>;
|
|
22
|
+
};
|
|
23
|
+
export type SessionStore = ReturnType<typeof createSessionStore>;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { Tables } from './config';
|
|
2
|
+
import { Queryable } from './query';
|
|
3
|
+
import { SpaceTokenAdapters } from '../identity';
|
|
4
|
+
/**
|
|
5
|
+
* The stored half of a space credential.
|
|
6
|
+
*
|
|
7
|
+
* Note what is NOT here: nothing creates a row. The space-token API rotates, re-scopes and revokes credentials for
|
|
8
|
+
* a space that already has one, and issuing a space's first credential happens when the space itself is created —
|
|
9
|
+
* which is the deployment's event, not auth's. `createSpaceToken` on the store's `admin` surface does it.
|
|
10
|
+
*/
|
|
11
|
+
export declare const createSpaceTokenStore: (db: Queryable, t: Tables) => SpaceTokenAdapters;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { dropSchema } from './schema';
|
|
2
|
+
import { MysqlAdmin } from './admin';
|
|
3
|
+
import { MysqlConfig } from './config';
|
|
4
|
+
import { IdentityStore } from './identities';
|
|
5
|
+
import { SessionStore } from './sessions';
|
|
6
|
+
import { AccountAdapters, IdentityAdapters, SpaceTokenAdapters } from '../identity';
|
|
7
|
+
import { Pool } from 'mysql2/promise';
|
|
8
|
+
export interface MysqlStore {
|
|
9
|
+
/** The pool, for a deployment with queries of its own. Ended by `close()` unless it was handed in. */
|
|
10
|
+
pool: Pool;
|
|
11
|
+
/** The resolved, unprefixed-plus-prefix table names, so a migration tool or an error can name one. */
|
|
12
|
+
tables: Record<string, string>;
|
|
13
|
+
schemaVersion: number;
|
|
14
|
+
/**
|
|
15
|
+
* Both halves of what `createAuth` asks for, implemented. Spread your own on top to add what only you can answer
|
|
16
|
+
* — `sendMail` for the reset and validation flows, `exchangeCredential` for an external identity provider.
|
|
17
|
+
*/
|
|
18
|
+
authAdapters: IdentityAdapters & AccountAdapters;
|
|
19
|
+
/** For `createSpaceTokenApi`. Present whether or not this deployment issues space credentials. */
|
|
20
|
+
spaceTokenAdapters: SpaceTokenAdapters;
|
|
21
|
+
/** The account's signed-in devices: list them, end one, end the others. */
|
|
22
|
+
sessions: SessionStore;
|
|
23
|
+
/** Accounts at other identity providers. Storage only — whether two are the same person is your judgement. */
|
|
24
|
+
identities: IdentityStore;
|
|
25
|
+
/** Seeding and administration — roles, permissions, memberships, a space's first credential. */
|
|
26
|
+
admin: MysqlAdmin;
|
|
27
|
+
/**
|
|
28
|
+
* Removes this schema and nothing else — for a deployment that shared a database with other things and has
|
|
29
|
+
* stopped using it. Returns the tables it dropped. Refuses a database it was never migrated into.
|
|
30
|
+
*/
|
|
31
|
+
uninstall: (options?: {
|
|
32
|
+
force?: boolean;
|
|
33
|
+
}) => Promise<string[]>;
|
|
34
|
+
close: () => Promise<void>;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* An account store on MySQL, with the tables it needs.
|
|
38
|
+
*
|
|
39
|
+
* This is the batteries-included half of `createAuth`. A deployment that already has users implements the adapters
|
|
40
|
+
* against its own tables and never comes here; a deployment standing one up gets the schema, the queries and the
|
|
41
|
+
* traps already handled:
|
|
42
|
+
*
|
|
43
|
+
* ```ts
|
|
44
|
+
* const store = await createMysqlStore({ url: process.env.DATABASE_URL });
|
|
45
|
+
*
|
|
46
|
+
* const auth = createAuth({
|
|
47
|
+
* tokens: { keys, issuer },
|
|
48
|
+
* secret,
|
|
49
|
+
* adapters: store.authAdapters,
|
|
50
|
+
* });
|
|
51
|
+
* ```
|
|
52
|
+
*
|
|
53
|
+
* It connects to a MySQL server; it does not start one. Where the database lives is a deployment decision and one
|
|
54
|
+
* this cannot make well — a container in development, a managed instance in production, and neither of them
|
|
55
|
+
* something a library should be launching behind your back.
|
|
56
|
+
*/
|
|
57
|
+
export declare const createMysqlStore: (config: MysqlConfig) => Promise<MysqlStore>;
|
|
58
|
+
export { dropSchema };
|
|
59
|
+
/** The DDL, for a deployment whose database user may not run it — see `MysqlConfig.autoMigrate`. */
|
|
60
|
+
export declare const mysqlSchemaStatements: (tablePrefix: string, fromVersion?: number) => string[];
|
|
61
|
+
export { TABLE_NAMES, tableNames } from './config';
|
|
62
|
+
export { SCHEMA_VERSION } from './schema';
|
|
63
|
+
export type { MysqlConfig, TableKey, Tables } from './config';
|
|
64
|
+
export type { AccountSeed, MysqlAdmin, SpaceTokenSeed } from './admin';
|
|
65
|
+
export type { SessionStore } from './sessions';
|
|
66
|
+
export type { IdentityStore, LinkedIdentity } from './identities';
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { reachSpaceInside, reachOwnServer } from './inside';
|
|
2
|
+
export { isBlockedHost, privateOriginsOf, assertOutboundAllowed, fetchOutbound, cappedResponse } from './outboundGuard';
|
|
3
|
+
export type { OwnServer } from './inside';
|
|
4
|
+
export type { HostLookup, OutboundOptions } from './outboundGuard';
|
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
import net, { BlockList, isIP } from "node:net";
|
|
2
|
+
import { X509Certificate } from "node:crypto";
|
|
3
|
+
import tls from "node:tls";
|
|
4
|
+
import { lookup } from "node:dns/promises";
|
|
5
|
+
// src/outbound/inside.ts
|
|
6
|
+
/** Headers as a dispatch carries them — a record, name/value pairs flattened into one list, or pairs — plus one more. */
|
|
7
|
+
var withHeader = (headers, name, value) => {
|
|
8
|
+
const entries = [];
|
|
9
|
+
if (Array.isArray(headers)) for (let index = 0; index < headers.length; index += 2) entries.push([headers[index], headers[index + 1]]);
|
|
10
|
+
else if (headers && Symbol.iterator in headers) entries.push(...headers);
|
|
11
|
+
else if (headers) entries.push(...Object.entries(headers));
|
|
12
|
+
return {
|
|
13
|
+
...Object.fromEntries(entries),
|
|
14
|
+
[name]: value
|
|
15
|
+
};
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* How every OTHER host is reached once one of these dispatchers is the process's: as Node's own `fetch` reaches it,
|
|
19
|
+
* over HTTP/1.1. An undici connector offers HTTP/2 by default, and an answer that came back over h2 reached Node's
|
|
20
|
+
* `fetch` without its `content-encoding` — so nothing decoded it, and every API that compresses read as Brotli bytes.
|
|
21
|
+
*/
|
|
22
|
+
var elsewhere = (undici) => undici.buildConnector({ allowH2: false });
|
|
23
|
+
/**
|
|
24
|
+
* The space's own public address, reached from inside the network this runtime runs in: every request this process
|
|
25
|
+
* makes to the space's host — `fetch` and `WebSocket` alike, which share Node's dispatcher — connects to `insideUrl`
|
|
26
|
+
* instead, over plain HTTP, the space's host and the public protocol kept (`X-Forwarded-Proto`). It is the path a
|
|
27
|
+
* request takes once past the edge, without leaving to come back through it; the space's code keeps writing its public
|
|
28
|
+
* address, and nothing else it reaches changes.
|
|
29
|
+
*
|
|
30
|
+
* `undici` is imported here, when a runtime asks, and never with the module: loading the package installs a global
|
|
31
|
+
* dispatcher of its own, and this entry is loaded by the platform's page server too (`createRuntimeProxyStage`), whose
|
|
32
|
+
* every `fetch` must stay Node's.
|
|
33
|
+
*/
|
|
34
|
+
var reachSpaceInside = async ({ publicUrl, insideUrl }) => {
|
|
35
|
+
const outside = new URL(publicUrl);
|
|
36
|
+
const inside = new URL(insideUrl);
|
|
37
|
+
if (inside.protocol !== "http:") throw new Error(`A space is reached from inside over plain HTTP, not ${inside.protocol} (${insideUrl})`);
|
|
38
|
+
const undici = await import("undici");
|
|
39
|
+
const { Agent, setGlobalDispatcher } = undici;
|
|
40
|
+
const port = Number(inside.port || 80);
|
|
41
|
+
const protocol = outside.protocol.replace(":", "");
|
|
42
|
+
const connect = elsewhere(undici);
|
|
43
|
+
setGlobalDispatcher(new Agent({ connect: (options, callback) => {
|
|
44
|
+
if (options.hostname !== outside.hostname) {
|
|
45
|
+
connect(options, callback);
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
const socket = net.connect(port, inside.hostname);
|
|
49
|
+
socket.once("connect", () => callback(null, socket));
|
|
50
|
+
socket.once("error", (error) => callback(error, null));
|
|
51
|
+
} }).compose((dispatch) => (options, handler) => dispatch(new URL(String(options.origin)).hostname === outside.hostname ? {
|
|
52
|
+
...options,
|
|
53
|
+
headers: withHeader(options.headers, "x-forwarded-proto", protocol)
|
|
54
|
+
} : options, handler)));
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* A self-hosted server serving TLS itself, reached from its own process — the runtime calling its own MCP, a function
|
|
58
|
+
* calling a route of its own space: every request to its public address connects to its listener on this machine.
|
|
59
|
+
*
|
|
60
|
+
* Its certificate is usually a local one (mkcert, for a tablet on the Wi-Fi), which the browsers on that network were
|
|
61
|
+
* told to trust and Node was not, so these requests failed whatever the address said. They are taken when the peer
|
|
62
|
+
* presents exactly this server's certificate — its fingerprint, not a chain — and refused otherwise; nothing else the
|
|
63
|
+
* process reaches is verified any less.
|
|
64
|
+
*/
|
|
65
|
+
var reachOwnServer = async ({ publicUrl, listener, cert }) => {
|
|
66
|
+
const outside = new URL(publicUrl);
|
|
67
|
+
const outsidePort = outside.port || (outside.protocol === "https:" ? "443" : "80");
|
|
68
|
+
const own = new X509Certificate(cert).fingerprint256;
|
|
69
|
+
const undici = await import("undici");
|
|
70
|
+
const { Agent, setGlobalDispatcher } = undici;
|
|
71
|
+
const connect = elsewhere(undici);
|
|
72
|
+
setGlobalDispatcher(new Agent({ connect: (options, callback) => {
|
|
73
|
+
if (options.hostname !== outside.hostname || (options.port || outsidePort) !== outsidePort) {
|
|
74
|
+
connect(options, callback);
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
const socket = tls.connect({
|
|
78
|
+
host: listener.host,
|
|
79
|
+
port: listener.port,
|
|
80
|
+
...net.isIP(outside.hostname) ? {} : { servername: outside.hostname },
|
|
81
|
+
ALPNProtocols: ["http/1.1"],
|
|
82
|
+
rejectUnauthorized: false
|
|
83
|
+
});
|
|
84
|
+
socket.once("secureConnect", () => {
|
|
85
|
+
if (socket.getPeerX509Certificate()?.fingerprint256 !== own) {
|
|
86
|
+
socket.destroy();
|
|
87
|
+
callback(/* @__PURE__ */ new Error(`${outside.host} answered with a certificate that is not this server's`), null);
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
callback(null, socket);
|
|
91
|
+
});
|
|
92
|
+
socket.once("error", (error) => callback(error, null));
|
|
93
|
+
} }));
|
|
94
|
+
};
|
|
95
|
+
// src/outbound/outboundGuard.ts
|
|
96
|
+
/**
|
|
97
|
+
* Where a customer-authored request may go.
|
|
98
|
+
*
|
|
99
|
+
* Two things reach the outside world on somebody else's say-so: the `http.request` task, whose URL is typed into
|
|
100
|
+
* a flow, and the connector engine, whose `baseUrl` is typed into a manifest. Both run inside the cluster, from a
|
|
101
|
+
* trusted network position, which is what turns "fetch this URL for me" into a way to read the instance's cloud
|
|
102
|
+
* credentials at `169.254.169.254` or talk to Redis on `localhost`. One rule, in one place, for both of them.
|
|
103
|
+
*/
|
|
104
|
+
/**
|
|
105
|
+
* Every range that is never a public peer, as ranges rather than string patterns.
|
|
106
|
+
*
|
|
107
|
+
* A `BlockList` also judges an IPv4-mapped IPv6 address (`::ffff:7f00:1`) against the IPv4 rules, which is the form a
|
|
108
|
+
* URL parser turns `[::ffff:127.0.0.1]` into and a dual-stack socket happily connects to loopback. The prefix
|
|
109
|
+
* patterns this replaced matched neither that nor `::`, and matched DNS names that merely began with `fc` or `fe8`.
|
|
110
|
+
*/
|
|
111
|
+
var privateRanges = new BlockList();
|
|
112
|
+
var IPV4_RANGES = [
|
|
113
|
+
["0.0.0.0", 8],
|
|
114
|
+
["10.0.0.0", 8],
|
|
115
|
+
["100.64.0.0", 10],
|
|
116
|
+
["127.0.0.0", 8],
|
|
117
|
+
["169.254.0.0", 16],
|
|
118
|
+
["172.16.0.0", 12],
|
|
119
|
+
["192.0.0.0", 24],
|
|
120
|
+
["192.168.0.0", 16],
|
|
121
|
+
["198.18.0.0", 15],
|
|
122
|
+
["224.0.0.0", 4],
|
|
123
|
+
["240.0.0.0", 4]
|
|
124
|
+
];
|
|
125
|
+
var IPV6_RANGES = [
|
|
126
|
+
["::", 96],
|
|
127
|
+
["64:ff9b:1::", 48],
|
|
128
|
+
["fc00::", 7],
|
|
129
|
+
["fe80::", 10],
|
|
130
|
+
["ff00::", 8]
|
|
131
|
+
];
|
|
132
|
+
/** An IPv4 address as the two 16-bit groups it occupies inside an IPv6 one. */
|
|
133
|
+
var ipv4Groups = (address) => {
|
|
134
|
+
const [a = 0, b = 0, c = 0, d = 0] = address.split(".").map(Number);
|
|
135
|
+
return [(a << 8 | b).toString(16), (c << 8 | d).toString(16)];
|
|
136
|
+
};
|
|
137
|
+
/**
|
|
138
|
+
* The same private IPv4 ranges where IPv6 carries an IPv4 address inside it.
|
|
139
|
+
*
|
|
140
|
+
* NAT64 (`64:ff9b::/96`) is how an IPv6-only cluster reaches EVERY IPv4 host — DNS64 answers a public API with an address
|
|
141
|
+
* in it — so the prefix cannot be refused whole; what it carries is judged instead. 6to4 (`2002::/16`) carries its
|
|
142
|
+
* address in bits 16–47.
|
|
143
|
+
*/
|
|
144
|
+
var EMBEDDED_IPV4_RANGES = IPV4_RANGES.flatMap(([network, prefix]) => {
|
|
145
|
+
const [high, low] = ipv4Groups(network);
|
|
146
|
+
return [[`64:ff9b::${high}:${low}`, 96 + prefix], [`2002:${high}:${low}::`, 16 + prefix]];
|
|
147
|
+
});
|
|
148
|
+
IPV4_RANGES.forEach(([network, prefix]) => privateRanges.addSubnet(network, prefix, "ipv4"));
|
|
149
|
+
[...IPV6_RANGES, ...EMBEDDED_IPV4_RANGES].forEach(([network, prefix]) => privateRanges.addSubnet(network, prefix, "ipv6"));
|
|
150
|
+
var isBlockedName = (host) => host === "localhost" || host.endsWith(".localhost") || host.endsWith(".internal");
|
|
151
|
+
/**
|
|
152
|
+
* Whether a hostname — or an address a name resolved to — may never be the other end of an authored request.
|
|
153
|
+
*
|
|
154
|
+
* A NAME is only refused for what it says it is (`localhost`, `*.internal`); anything else about a name is decided by
|
|
155
|
+
* what it resolves to, in `assertOutboundAllowed`.
|
|
156
|
+
*/
|
|
157
|
+
var isBlockedHost = (hostname) => {
|
|
158
|
+
const host = hostname.toLowerCase().replace(/^\[|\]$/g, "").replace(/%.*$/, "");
|
|
159
|
+
const family = isIP(host);
|
|
160
|
+
if (family === 0) return isBlockedName(host);
|
|
161
|
+
return privateRanges.check(host, family === 6 ? "ipv6" : "ipv4");
|
|
162
|
+
};
|
|
163
|
+
var resolveAll = (hostname) => lookup(hostname, {
|
|
164
|
+
all: true,
|
|
165
|
+
verbatim: true
|
|
166
|
+
});
|
|
167
|
+
/**
|
|
168
|
+
* The deployment's own origins as `new URL(…).origin` writes them, refusing what is not one — said when the server is
|
|
169
|
+
* built, rather than as every request that should have reached it failing.
|
|
170
|
+
*/
|
|
171
|
+
var privateOriginsOf = (origins) => (origins ?? []).map((origin) => {
|
|
172
|
+
let url;
|
|
173
|
+
try {
|
|
174
|
+
url = new URL(origin);
|
|
175
|
+
} catch {
|
|
176
|
+
throw new Error(`outbound.privateOrigins: "${origin}" is not an origin — write it as http://host:port`);
|
|
177
|
+
}
|
|
178
|
+
if (url.protocol !== "http:" && url.protocol !== "https:" || url.origin !== origin.replace(/\/$/, "")) throw new Error(`outbound.privateOrigins: "${origin}" is not an origin — write it as http://host:port, no path`);
|
|
179
|
+
return url.origin;
|
|
180
|
+
});
|
|
181
|
+
/**
|
|
182
|
+
* Checks the URL an authored document asked for, including what its hostname RESOLVES to — unless it is one of the
|
|
183
|
+
* origins the deployment names as its own (`privateOrigins`).
|
|
184
|
+
*
|
|
185
|
+
* The literal check alone was never enough and said so: `http://metadata.example.com/` is a public-looking name
|
|
186
|
+
* whose A record can be `169.254.169.254`, and nothing about the string gives that away. So the name is resolved
|
|
187
|
+
* and every address it answers is judged — a name that resolves to a private address is refused whatever it is
|
|
188
|
+
* spelled like.
|
|
189
|
+
*
|
|
190
|
+
* A name that does not resolve is ALLOWED through: there is nothing to judge, and the request is about to fail on
|
|
191
|
+
* its own with a better error than this could give. What remains open is DNS rebinding — an attacker's own server
|
|
192
|
+
* answering a public address here and a private one when the socket is opened a moment later — which is closed
|
|
193
|
+
* only by resolving and connecting to the same address, and that belongs in the transport rather than here.
|
|
194
|
+
*/
|
|
195
|
+
var assertOutboundAllowed = async (url, { lookup = resolveAll, privateOrigins = [] } = {}) => {
|
|
196
|
+
if (url.protocol !== "https:" && url.protocol !== "http:") throw new Error(`Request protocol "${url.protocol}" is not allowed`);
|
|
197
|
+
if (privateOrigins.includes(url.origin)) return;
|
|
198
|
+
if (isBlockedHost(url.hostname)) throw new Error("Request host is not allowed");
|
|
199
|
+
let addresses;
|
|
200
|
+
try {
|
|
201
|
+
addresses = await lookup(url.hostname.replace(/^\[|\]$/g, ""));
|
|
202
|
+
} catch {
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
if (addresses.some(({ address }) => isBlockedHost(address))) throw new Error("Request host is not allowed");
|
|
206
|
+
};
|
|
207
|
+
var MAX_REDIRECTS = 5;
|
|
208
|
+
var REDIRECT_STATUSES = [
|
|
209
|
+
301,
|
|
210
|
+
302,
|
|
211
|
+
303,
|
|
212
|
+
307,
|
|
213
|
+
308
|
|
214
|
+
];
|
|
215
|
+
/** What the Fetch standard strips when a redirect leaves the origin that was given them. */
|
|
216
|
+
var CROSS_ORIGIN_HEADERS = [
|
|
217
|
+
"authorization",
|
|
218
|
+
"cookie",
|
|
219
|
+
"proxy-authorization"
|
|
220
|
+
];
|
|
221
|
+
var BODY_HEADERS = [
|
|
222
|
+
"content-type",
|
|
223
|
+
"content-length",
|
|
224
|
+
"content-encoding",
|
|
225
|
+
"content-language",
|
|
226
|
+
"content-location"
|
|
227
|
+
];
|
|
228
|
+
/**
|
|
229
|
+
* The request a redirect continues as — the rules `fetch` itself follows, applied by hand because it no longer does.
|
|
230
|
+
*
|
|
231
|
+
* A 303, and a 301/302 answering a POST, become a bodiless GET; 307 and 308 repeat the request exactly. Leaving the
|
|
232
|
+
* origin drops the headers the Fetch standard drops, and only those: a key the author put in a header of its own
|
|
233
|
+
* travels on as it did before, and the author already decides where it is sent.
|
|
234
|
+
*/
|
|
235
|
+
var redirectedInit = (init, status, crossOrigin) => {
|
|
236
|
+
const method = (init.method ?? "GET").toUpperCase();
|
|
237
|
+
const becomesGet = status === 303 && method !== "HEAD" || (status === 301 || status === 302) && method === "POST";
|
|
238
|
+
const headers = new Headers(init.headers);
|
|
239
|
+
if (crossOrigin) CROSS_ORIGIN_HEADERS.forEach((name) => headers.delete(name));
|
|
240
|
+
if (!becomesGet) return {
|
|
241
|
+
...init,
|
|
242
|
+
headers
|
|
243
|
+
};
|
|
244
|
+
BODY_HEADERS.forEach((name) => headers.delete(name));
|
|
245
|
+
return {
|
|
246
|
+
...init,
|
|
247
|
+
method: "GET",
|
|
248
|
+
body: void 0,
|
|
249
|
+
headers
|
|
250
|
+
};
|
|
251
|
+
};
|
|
252
|
+
/**
|
|
253
|
+
* Sends an authored request, judging EVERY hop it takes by `assertOutboundAllowed`.
|
|
254
|
+
*
|
|
255
|
+
* Checking the URL and handing it to `fetch` judged only the first hop: `fetch` follows redirects on its own, so a
|
|
256
|
+
* public server answering `302 Location: http://169.254.169.254/` took the request wherever it liked. Redirects are
|
|
257
|
+
* therefore taken manually and each destination is checked before anything is sent to it.
|
|
258
|
+
*
|
|
259
|
+
* `base` is the caller's own transport — the action runner's is budgeted and capped — so every hop is also counted
|
|
260
|
+
* against whatever that transport enforces.
|
|
261
|
+
*/
|
|
262
|
+
var fetchOutbound = async (base, url, init = {}, options = {}) => {
|
|
263
|
+
let target = url;
|
|
264
|
+
let request = init;
|
|
265
|
+
for (let hop = 0;; hop += 1) {
|
|
266
|
+
await assertOutboundAllowed(target, options);
|
|
267
|
+
const response = await base(target.toString(), {
|
|
268
|
+
...request,
|
|
269
|
+
redirect: "manual"
|
|
270
|
+
});
|
|
271
|
+
const location = response.headers.get("location");
|
|
272
|
+
if (!REDIRECT_STATUSES.includes(response.status) || !location) return response;
|
|
273
|
+
await response.body?.cancel();
|
|
274
|
+
if (hop >= MAX_REDIRECTS) throw new Error(`Request followed more than ${MAX_REDIRECTS} redirects`);
|
|
275
|
+
const next = new URL(location, target);
|
|
276
|
+
request = redirectedInit(request, response.status, next.origin !== target.origin);
|
|
277
|
+
target = next;
|
|
278
|
+
}
|
|
279
|
+
};
|
|
280
|
+
/**
|
|
281
|
+
* Holds an answer to what its reader is allowed to carry — an action's run, a page server's read of another site.
|
|
282
|
+
*
|
|
283
|
+
* Two checks rather than one, because a body arrives in two ways. `Content-Length` is refused before a byte is
|
|
284
|
+
* read, which is the cheap half; a chunked answer that declares nothing is counted AS it streams and errored the
|
|
285
|
+
* moment it goes over — so the ceiling holds for a backend that lies about its size or never states one.
|
|
286
|
+
*
|
|
287
|
+
* The cap is on one response and not on the run or the page: it exists so that a single answer cannot be unbounded, which is
|
|
288
|
+
* a different failure from a flow that makes many small calls (that is `maxRequests`).
|
|
289
|
+
*/
|
|
290
|
+
var cappedResponse = (response, maxBytes, refuse, alsoCount) => {
|
|
291
|
+
const declared = Number(response.headers.get("content-length") ?? "");
|
|
292
|
+
if (Number.isFinite(declared) && declared > maxBytes) throw refuse(`Response is larger than the ${String(maxBytes)} byte budget`);
|
|
293
|
+
if (!response.body) return response;
|
|
294
|
+
let seen = 0;
|
|
295
|
+
const counted = response.body.pipeThrough(new TransformStream({ transform: (chunk, controller) => {
|
|
296
|
+
seen += chunk.byteLength;
|
|
297
|
+
if (seen > maxBytes) {
|
|
298
|
+
controller.error(refuse(`Response exceeded the ${String(maxBytes)} byte budget`));
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
const spent = alsoCount?.(chunk.byteLength);
|
|
302
|
+
if (spent) {
|
|
303
|
+
controller.error(refuse(spent));
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
controller.enqueue(chunk);
|
|
307
|
+
} }));
|
|
308
|
+
return new Response(counted, {
|
|
309
|
+
status: response.status,
|
|
310
|
+
statusText: response.statusText,
|
|
311
|
+
headers: response.headers
|
|
312
|
+
});
|
|
313
|
+
};
|
|
314
|
+
export { assertOutboundAllowed, cappedResponse, fetchOutbound, isBlockedHost, privateOriginsOf, reachOwnServer, reachSpaceInside };
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The space's own public address, reached from inside the network this runtime runs in: every request this process
|
|
3
|
+
* makes to the space's host — `fetch` and `WebSocket` alike, which share Node's dispatcher — connects to `insideUrl`
|
|
4
|
+
* instead, over plain HTTP, the space's host and the public protocol kept (`X-Forwarded-Proto`). It is the path a
|
|
5
|
+
* request takes once past the edge, without leaving to come back through it; the space's code keeps writing its public
|
|
6
|
+
* address, and nothing else it reaches changes.
|
|
7
|
+
*
|
|
8
|
+
* `undici` is imported here, when a runtime asks, and never with the module: loading the package installs a global
|
|
9
|
+
* dispatcher of its own, and this entry is loaded by the platform's page server too (`createRuntimeProxyStage`), whose
|
|
10
|
+
* every `fetch` must stay Node's.
|
|
11
|
+
*/
|
|
12
|
+
export declare const reachSpaceInside: ({ publicUrl, insideUrl }: {
|
|
13
|
+
publicUrl: string;
|
|
14
|
+
insideUrl: string;
|
|
15
|
+
}) => Promise<void>;
|
|
16
|
+
export type OwnServer = {
|
|
17
|
+
/** Where people reach this server — the address its code writes and fetches. */
|
|
18
|
+
publicUrl: string;
|
|
19
|
+
/** Where this machine reaches it: the address and port it listens on. */
|
|
20
|
+
listener: {
|
|
21
|
+
host: string;
|
|
22
|
+
port: number;
|
|
23
|
+
};
|
|
24
|
+
/** The certificate it serves, PEM: the one a connection to it has to present to be taken as this server. */
|
|
25
|
+
cert: string | Buffer;
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* A self-hosted server serving TLS itself, reached from its own process — the runtime calling its own MCP, a function
|
|
29
|
+
* calling a route of its own space: every request to its public address connects to its listener on this machine.
|
|
30
|
+
*
|
|
31
|
+
* Its certificate is usually a local one (mkcert, for a tablet on the Wi-Fi), which the browsers on that network were
|
|
32
|
+
* told to trust and Node was not, so these requests failed whatever the address said. They are taken when the peer
|
|
33
|
+
* presents exactly this server's certificate — its fingerprint, not a chain — and refused otherwise; nothing else the
|
|
34
|
+
* process reaches is verified any less.
|
|
35
|
+
*/
|
|
36
|
+
export declare const reachOwnServer: ({ publicUrl, listener, cert }: OwnServer) => Promise<void>;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether a hostname — or an address a name resolved to — may never be the other end of an authored request.
|
|
3
|
+
*
|
|
4
|
+
* A NAME is only refused for what it says it is (`localhost`, `*.internal`); anything else about a name is decided by
|
|
5
|
+
* what it resolves to, in `assertOutboundAllowed`.
|
|
6
|
+
*/
|
|
7
|
+
export declare const isBlockedHost: (hostname: string) => boolean;
|
|
8
|
+
export type HostLookup = (hostname: string) => Promise<{
|
|
9
|
+
address: string;
|
|
10
|
+
}[]>;
|
|
11
|
+
/**
|
|
12
|
+
* What the deployment says of the requests its spaces write.
|
|
13
|
+
*
|
|
14
|
+
* `privateOrigins` are the origins on its own network an authored request may reach all the same — its storage, its
|
|
15
|
+
* CDN, its API, put there by whoever runs it and named in its configuration, never by a document. Every other private
|
|
16
|
+
* address stays closed: a self-hosted server whose files live on a local S3 serves them to its pages without opening
|
|
17
|
+
* the network they sit in. `lookup` is how a name is resolved, a test's to replace.
|
|
18
|
+
*/
|
|
19
|
+
export type OutboundOptions = {
|
|
20
|
+
lookup?: HostLookup;
|
|
21
|
+
privateOrigins?: readonly string[];
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* The deployment's own origins as `new URL(…).origin` writes them, refusing what is not one — said when the server is
|
|
25
|
+
* built, rather than as every request that should have reached it failing.
|
|
26
|
+
*/
|
|
27
|
+
export declare const privateOriginsOf: (origins: readonly string[] | undefined) => string[];
|
|
28
|
+
/**
|
|
29
|
+
* Checks the URL an authored document asked for, including what its hostname RESOLVES to — unless it is one of the
|
|
30
|
+
* origins the deployment names as its own (`privateOrigins`).
|
|
31
|
+
*
|
|
32
|
+
* The literal check alone was never enough and said so: `http://metadata.example.com/` is a public-looking name
|
|
33
|
+
* whose A record can be `169.254.169.254`, and nothing about the string gives that away. So the name is resolved
|
|
34
|
+
* and every address it answers is judged — a name that resolves to a private address is refused whatever it is
|
|
35
|
+
* spelled like.
|
|
36
|
+
*
|
|
37
|
+
* A name that does not resolve is ALLOWED through: there is nothing to judge, and the request is about to fail on
|
|
38
|
+
* its own with a better error than this could give. What remains open is DNS rebinding — an attacker's own server
|
|
39
|
+
* answering a public address here and a private one when the socket is opened a moment later — which is closed
|
|
40
|
+
* only by resolving and connecting to the same address, and that belongs in the transport rather than here.
|
|
41
|
+
*/
|
|
42
|
+
export declare const assertOutboundAllowed: (url: URL, { lookup, privateOrigins }?: OutboundOptions) => Promise<void>;
|
|
43
|
+
/**
|
|
44
|
+
* Sends an authored request, judging EVERY hop it takes by `assertOutboundAllowed`.
|
|
45
|
+
*
|
|
46
|
+
* Checking the URL and handing it to `fetch` judged only the first hop: `fetch` follows redirects on its own, so a
|
|
47
|
+
* public server answering `302 Location: http://169.254.169.254/` took the request wherever it liked. Redirects are
|
|
48
|
+
* therefore taken manually and each destination is checked before anything is sent to it.
|
|
49
|
+
*
|
|
50
|
+
* `base` is the caller's own transport — the action runner's is budgeted and capped — so every hop is also counted
|
|
51
|
+
* against whatever that transport enforces.
|
|
52
|
+
*/
|
|
53
|
+
export declare const fetchOutbound: (base: typeof fetch, url: URL, init?: RequestInit, options?: OutboundOptions) => Promise<Response>;
|
|
54
|
+
/**
|
|
55
|
+
* Holds an answer to what its reader is allowed to carry — an action's run, a page server's read of another site.
|
|
56
|
+
*
|
|
57
|
+
* Two checks rather than one, because a body arrives in two ways. `Content-Length` is refused before a byte is
|
|
58
|
+
* read, which is the cheap half; a chunked answer that declares nothing is counted AS it streams and errored the
|
|
59
|
+
* moment it goes over — so the ceiling holds for a backend that lies about its size or never states one.
|
|
60
|
+
*
|
|
61
|
+
* The cap is on one response and not on the run or the page: it exists so that a single answer cannot be unbounded, which is
|
|
62
|
+
* a different failure from a flow that makes many small calls (that is `maxRequests`).
|
|
63
|
+
*/
|
|
64
|
+
export declare const cappedResponse: (response: Response, maxBytes: number, refuse: (message: string) => Error,
|
|
65
|
+
/**
|
|
66
|
+
* A second budget the same bytes are counted against — a run's, across all of its answers. Told each chunk as it
|
|
67
|
+
* arrives; a message back refuses the answer with it.
|
|
68
|
+
*/
|
|
69
|
+
alsoCount?: (bytes: number) => string | undefined) => Response;
|