@coffre/client 0.10.2 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/dpop-C5Zyaixy.d.ts +183 -0
- package/dist/dpop.d.ts +2 -0
- package/dist/dpop.js +290 -0
- package/dist/{index-D86fJBDd.d.ts → index--nfmYCFv.d.ts} +222 -13
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -485
- package/dist/routes.d.ts +1 -1
- package/dist/routes.js +13 -0
- package/dist/src-CDyZe9vW.js +490 -0
- package/dist/workload-9LPBYMmN.d.ts +250 -0
- package/dist/workload-postgres.d.ts +54 -0
- package/dist/workload-postgres.js +210 -0
- package/dist/workload-w4QPSyjj.js +1018 -0
- package/dist/workload.d.ts +3 -0
- package/dist/workload.js +3 -0
- package/package.json +16 -1
- package/src/api.ts +178 -10
- package/src/dpop.ts +301 -0
- package/src/index.ts +3 -1
- package/src/routes.ts +10 -0
- package/src/workload-postgres.ts +254 -0
- package/src/workload-proofs.ts +365 -0
- package/src/workload.ts +711 -0
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
import { o as PublicJwk } from "./dpop-C5Zyaixy.js";
|
|
2
|
+
//#region src/workload-proofs.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* How a workload proves who it is, once per session (docs/design/workload-access.md,
|
|
5
|
+
* section 4): each platform's own proof, asked for afresh at each exchange,
|
|
6
|
+
* and bound to the session's key wherever the platform lets the caller say
|
|
7
|
+
* so. `workload({ proof })` takes one of these:
|
|
8
|
+
*
|
|
9
|
+
* kubernetes() the projected service account token, read from its file
|
|
10
|
+
* aws() a GetCallerIdentity signed with the role's own credentials
|
|
11
|
+
* gcp() the metadata server's ID token, its audience naming the key
|
|
12
|
+
* azure({ audience }) the managed identity's token for coffre's Entra application
|
|
13
|
+
* fly() the machine's OIDC token, its audience naming the key
|
|
14
|
+
* vercel() the function's OIDC token, exchanged for one naming the key
|
|
15
|
+
* github() the Actions runner's ID token, its audience naming the key
|
|
16
|
+
* oidc(token) any other ID token: GitLab's `id_tokens`, a custom issuer's
|
|
17
|
+
* enrollment(code) a code CI minted for this deploy, on a platform that signs nothing
|
|
18
|
+
*
|
|
19
|
+
* A proof reads only its platform's own variables and endpoints (AWS's,
|
|
20
|
+
* GitHub's runner's, Azure's identity endpoint), never one of coffre's, and
|
|
21
|
+
* nothing here writes anything anywhere. No dependency: `fetch`, WebCrypto,
|
|
22
|
+
* and Node's `fs` and `http` loaded only by the proofs that read a file or
|
|
23
|
+
* a socket.
|
|
24
|
+
*/
|
|
25
|
+
/** What the exchange is sent as `proof`: an ID token, a signed `GetCallerIdentity`, or an enrollment code. */
|
|
26
|
+
type PlatformProof = {
|
|
27
|
+
oidc: string;
|
|
28
|
+
} | {
|
|
29
|
+
aws: {
|
|
30
|
+
url: string;
|
|
31
|
+
headers: Record<string, string>;
|
|
32
|
+
body: string;
|
|
33
|
+
};
|
|
34
|
+
} | {
|
|
35
|
+
enrollment: string;
|
|
36
|
+
};
|
|
37
|
+
type Fetch$1 = (input: string, init?: RequestInit) => Promise<Response>;
|
|
38
|
+
/** What a proof is given at each exchange: the instance and the key to name, and how to reach its platform. */
|
|
39
|
+
type ProofContext = {
|
|
40
|
+
/** The instance's URL as its audience: `https://secrets.acme.example`. */
|
|
41
|
+
audience: string;
|
|
42
|
+
/** The session key's thumbprint, which a key-naming audience carries: `<audience>#jkt=<jkt>`. */
|
|
43
|
+
jkt: string;
|
|
44
|
+
fetch: Fetch$1;
|
|
45
|
+
/** Where the SDK says what it waits for: stderr unless the app said otherwise. */
|
|
46
|
+
log: (line: string) => void;
|
|
47
|
+
/** Aborted when the session closes: a proof that waits (a spent token's next) stops waiting, and one that asks a socket (Fly's) stops asking. `fetch` ends with it already. */
|
|
48
|
+
signal?: AbortSignal;
|
|
49
|
+
};
|
|
50
|
+
interface Proof {
|
|
51
|
+
/** Which platform, as messages name it. */
|
|
52
|
+
readonly name: string;
|
|
53
|
+
/** An enrollment session's expiry is its liveness: it renews every 30 seconds, and can never re-prove past its code's end. */
|
|
54
|
+
readonly kind: 'oidc' | 'aws' | 'enrollment';
|
|
55
|
+
/** A fresh proof, for this key at this instance. */
|
|
56
|
+
prove(context: ProofContext): Promise<PlatformProof>;
|
|
57
|
+
/**
|
|
58
|
+
* After the exchange said the proof was spent (`replayed`): wait until a
|
|
59
|
+
* fresh one exists, as the kubelet writes a projected token's next, and
|
|
60
|
+
* say whether one does. Only a proof whose platform hands out new ones
|
|
61
|
+
* has it.
|
|
62
|
+
*/
|
|
63
|
+
spent?(context: ProofContext): Promise<boolean>;
|
|
64
|
+
}
|
|
65
|
+
/** `<audience>#jkt=<thumbprint>`: an audience only this key can use (section 4.2). */
|
|
66
|
+
declare function keyAudience(context: ProofContext): string;
|
|
67
|
+
/** The default projected token's path, as docs/workloads.md mounts it. */
|
|
68
|
+
declare const KUBERNETES_TOKEN = "/var/run/secrets/coffre/token";
|
|
69
|
+
/**
|
|
70
|
+
* A Kubernetes projected service account token, read from its file before
|
|
71
|
+
* each exchange: the pod spec's `serviceAccountToken` with coffre's URL as
|
|
72
|
+
* its `audience`. Such a token is spent once used. If the exchange finds it
|
|
73
|
+
* spent (a restarted process reading the file again), this waits for the
|
|
74
|
+
* kubelet's next, which it writes at 80% of the token's life, watching the
|
|
75
|
+
* file for up to 10 minutes.
|
|
76
|
+
*/
|
|
77
|
+
declare function kubernetes(path?: string): Proof;
|
|
78
|
+
/** AWS credentials, as the AWS SDK's providers give them. */
|
|
79
|
+
type AwsCredentials = {
|
|
80
|
+
accessKeyId: string;
|
|
81
|
+
secretAccessKey: string;
|
|
82
|
+
sessionToken?: string;
|
|
83
|
+
};
|
|
84
|
+
/**
|
|
85
|
+
* A `GetCallerIdentity` request, signed with the workload's own role
|
|
86
|
+
* credentials, for coffre to send STS (section 4.3). The credentials never
|
|
87
|
+
* leave: coffre gets the URL, the headers and the body, and the signature
|
|
88
|
+
* covers `x-coffre-key`, so the proof works with this session's key only.
|
|
89
|
+
*
|
|
90
|
+
* The credentials are the given ones, an AWS SDK provider's
|
|
91
|
+
* (`aws({ credentials: fromNodeProviderChain() })`), or else, in order, the
|
|
92
|
+
* environment's, the ECS container endpoint's, or EC2's instance metadata
|
|
93
|
+
* (IMDSv2). The region is `AWS_REGION`'s, for its regional STS host, unless
|
|
94
|
+
* given; without one, the global host.
|
|
95
|
+
*/
|
|
96
|
+
declare function aws(options?: {
|
|
97
|
+
credentials?: AwsCredentials | (() => Promise<AwsCredentials>);
|
|
98
|
+
region?: string;
|
|
99
|
+
}): Proof;
|
|
100
|
+
/** Google Cloud's metadata server's ID token for the default service account, its audience naming the key: Cloud Run, GKE, GCE. */
|
|
101
|
+
declare function gcp(): Proof;
|
|
102
|
+
/**
|
|
103
|
+
* An Azure managed identity's token for coffre's Entra application, its
|
|
104
|
+
* `audience` (`api://coffre-acme`): from App Service's and Functions'
|
|
105
|
+
* identity endpoint, or else IMDS. `clientId` picks a user-assigned
|
|
106
|
+
* identity. Entra mints only for a registered audience, so the token cannot
|
|
107
|
+
* name the key, and repeats until it expires (section 4.2).
|
|
108
|
+
*/
|
|
109
|
+
declare function azure(options: {
|
|
110
|
+
audience: string;
|
|
111
|
+
clientId?: string;
|
|
112
|
+
}): Proof;
|
|
113
|
+
/** A Fly Machine's OIDC token, from its `/.fly/api` socket, its audience naming the key. */
|
|
114
|
+
declare function fly(socketPath?: string): Proof;
|
|
115
|
+
/**
|
|
116
|
+
* A Vercel function's OIDC token, exchanged at Vercel for one whose audience
|
|
117
|
+
* names the key, as `@vercel/oidc` does, asked afresh for each proof. The
|
|
118
|
+
* function's own token is the file `VERCEL_OIDC_TOKEN_FILE` names, or else
|
|
119
|
+
* `VERCEL_OIDC_TOKEN`, unless given: per request, from the
|
|
120
|
+
* `x-vercel-oidc-token` header, as `vercel(() => headers.get(…))`.
|
|
121
|
+
*/
|
|
122
|
+
declare function vercel(token?: string | (() => string | Promise<string>)): Proof;
|
|
123
|
+
/** A GitHub Actions job's ID token, from its runner, its audience naming the key: the job needs `permissions: id-token: write`. */
|
|
124
|
+
declare function github(): Proof;
|
|
125
|
+
/**
|
|
126
|
+
* Any other ID token, as given, or asked for at each exchange: GitLab's
|
|
127
|
+
* `id_tokens` entry, whose `aud` is coffre's URL, or a custom issuer's. A
|
|
128
|
+
* token is spent once used, so a given string proves one session.
|
|
129
|
+
*/
|
|
130
|
+
declare function oidc(token: string | (() => string | Promise<string>), name?: string): Proof;
|
|
131
|
+
/**
|
|
132
|
+
* An enrollment code (section 4.4), on a platform that signs nothing:
|
|
133
|
+
* Railway, Render, a VM. Once given, the code leaves `process.env`, under
|
|
134
|
+
* whatever name held it, so the app's own dumps of its environment no
|
|
135
|
+
* longer show it; the platform's store still holds it.
|
|
136
|
+
*/
|
|
137
|
+
declare function enrollment(code: string | undefined): Proof;
|
|
138
|
+
//#endregion
|
|
139
|
+
//#region src/workload.d.ts
|
|
140
|
+
type Fetch = typeof fetch;
|
|
141
|
+
type WorkloadOptions = {
|
|
142
|
+
/** The instance: `https://secrets.acme.example`. */
|
|
143
|
+
url: string;
|
|
144
|
+
/** The service account the workload signs in as: `api-prod`, or `token:api-prod`. */
|
|
145
|
+
service: string;
|
|
146
|
+
/** How it proves who it is: `kubernetes()`, `aws()`, `gcp()`, `enrollment(code)`… (`./workload-proofs.ts`). */
|
|
147
|
+
proof: Proof;
|
|
148
|
+
/** Which of the binding's environments `url`, `credential` and `read` mean, when it has several: `market/prod`. */
|
|
149
|
+
place?: string;
|
|
150
|
+
fetch?: Fetch;
|
|
151
|
+
/** Where it says what it waits for (a full code, an approval, a spent token): stderr unless set. */
|
|
152
|
+
log?: (line: string) => void;
|
|
153
|
+
/** `false` for a process that ends its own way, and calls `close()` itself: no logout on SIGTERM. */
|
|
154
|
+
sigterm?: boolean;
|
|
155
|
+
};
|
|
156
|
+
type NarrowOptions = {
|
|
157
|
+
places?: string[];
|
|
158
|
+
credentials?: string[];
|
|
159
|
+
methods?: string[];
|
|
160
|
+
/** Path prefixes of the upstream, matched by whole segments: `/v1/refunds`. */
|
|
161
|
+
paths?: string[];
|
|
162
|
+
/** Seconds; never past the parent's end. */
|
|
163
|
+
expiresIn?: number;
|
|
164
|
+
/** What the service's page calls it: `refund-agent`. */
|
|
165
|
+
label?: string;
|
|
166
|
+
};
|
|
167
|
+
interface Workload {
|
|
168
|
+
readonly service: string;
|
|
169
|
+
/** The environments the session reaches. */
|
|
170
|
+
readonly places: readonly string[];
|
|
171
|
+
/**
|
|
172
|
+
* A `fetch` that signs every request under `<url>/use/` and passes anything
|
|
173
|
+
* else through untouched: give it to any SDK that takes one.
|
|
174
|
+
*/
|
|
175
|
+
readonly fetch: Fetch;
|
|
176
|
+
/** A credential's URL on coffre's proxy, an SDK's base URL: `<url>/use/<name>`, or `<url>/use/<project>/<env>/<name>` with several places. */
|
|
177
|
+
url(name: string): string;
|
|
178
|
+
credential(name: string): UsedCredential;
|
|
179
|
+
/** The escape hatch: a plain value, or one the binding lists in `reads`. Anything else rejects with `use_only`. */
|
|
180
|
+
read(key: string): Promise<string>;
|
|
181
|
+
/**
|
|
182
|
+
* A session with less authority (section 8.4), for a part of the app that
|
|
183
|
+
* needs less: in this process, a `Workload` of its own key; for another
|
|
184
|
+
* process, which made the key and sends only its public half, the child's
|
|
185
|
+
* token, which that process uses with its own key.
|
|
186
|
+
*/
|
|
187
|
+
narrow(options: NarrowOptions & {
|
|
188
|
+
key: PublicJwk;
|
|
189
|
+
}): Promise<{
|
|
190
|
+
token: string;
|
|
191
|
+
expiresAt: string;
|
|
192
|
+
}>;
|
|
193
|
+
narrow(options: NarrowOptions): Promise<Workload>;
|
|
194
|
+
/** Logs out: the session ends now, and its children with it. */
|
|
195
|
+
close(): Promise<void>;
|
|
196
|
+
}
|
|
197
|
+
interface UsedCredential {
|
|
198
|
+
/** `<credential's URL>/<path>`, signed: the proxy forwards it to the upstream with the real key. */
|
|
199
|
+
fetch(path: string, init?: RequestInit): Promise<Response>;
|
|
200
|
+
/** A signature by a signer's private key, which stays in coffre: base64url, as `credential.sign` gives. */
|
|
201
|
+
sign(message: string | Uint8Array): Promise<string>;
|
|
202
|
+
/** Whether `signature` is a verifier's over `message`: an inbound webhook's, checked without reading its secret. */
|
|
203
|
+
verify(message: string | Uint8Array, signature: string): Promise<boolean>;
|
|
204
|
+
/** A presigned GET or HEAD of `path` under an AWS-signed credential's upstream: the upstream's own URL, for anyone until `expiresAt`. */
|
|
205
|
+
presign(path: string, options?: {
|
|
206
|
+
expiresIn?: number;
|
|
207
|
+
method?: 'GET' | 'HEAD';
|
|
208
|
+
query?: Record<string, string>;
|
|
209
|
+
}): Promise<{
|
|
210
|
+
url: string;
|
|
211
|
+
expiresAt: string;
|
|
212
|
+
}>;
|
|
213
|
+
/** A short-lived child of a minter (an AWS session, a GitHub installation token), where the binding lists it. */
|
|
214
|
+
mint<T = Record<string, string>>(): Promise<T & {
|
|
215
|
+
expiresAt: string;
|
|
216
|
+
}>;
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* Sign in as `service`, with `proof`, and hold the session for as long as
|
|
220
|
+
* the process runs. Rejects if the first exchange is refused.
|
|
221
|
+
*/
|
|
222
|
+
declare function workload(options: WorkloadOptions): Promise<Workload>;
|
|
223
|
+
/**
|
|
224
|
+
* The headers that sign a WebSocket's upgrade to `url` (a tunnel's), made
|
|
225
|
+
* outside `coffre.fetch`: the session, and a proof of a GET at its `https`
|
|
226
|
+
* form with a nonce fresh enough that the gate takes it, since an upgrade
|
|
227
|
+
* refused cannot be told why and sent again.
|
|
228
|
+
*/
|
|
229
|
+
declare function upgradeHeaders(coffre: Workload, url: string): Promise<Record<string, string>>;
|
|
230
|
+
/**
|
|
231
|
+
* Say that coffre refused an upgrade, or that it never opened: its nonce may
|
|
232
|
+
* be the gate's no longer, so the next upgrade, which cannot be sent again
|
|
233
|
+
* either, first asks for the newest.
|
|
234
|
+
*/
|
|
235
|
+
declare function upgradeRefused(coffre: Workload): void;
|
|
236
|
+
/**
|
|
237
|
+
* An AWS SDK credential provider over delivered minting (section 7.2): a
|
|
238
|
+
* minter's short-lived children, where the binding lists it, each kept
|
|
239
|
+
* until a minute before it expires.
|
|
240
|
+
*
|
|
241
|
+
* const s3 = new S3Client({ region: 'eu-west-3', credentials: fromCoffre(coffre, 'aws') });
|
|
242
|
+
*/
|
|
243
|
+
declare function fromCoffre(coffre: Workload, minter: string): () => Promise<{
|
|
244
|
+
accessKeyId: string;
|
|
245
|
+
secretAccessKey: string;
|
|
246
|
+
sessionToken?: string;
|
|
247
|
+
expiration: Date;
|
|
248
|
+
}>;
|
|
249
|
+
//#endregion
|
|
250
|
+
export { vercel as C, oidc as S, fly as _, fromCoffre as a, keyAudience as b, workload as c, PlatformProof as d, Proof as f, enrollment as g, azure as h, WorkloadOptions as i, AwsCredentials as l, aws as m, UsedCredential as n, upgradeHeaders as o, ProofContext as p, Workload as r, upgradeRefused as s, NarrowOptions as t, KUBERNETES_TOKEN as u, gcp as v, kubernetes as x, github as y };
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { r as Workload } from "./workload-9LPBYMmN.js";
|
|
2
|
+
import { Buffer } from "node:buffer";
|
|
3
|
+
import { Duplex } from "node:stream";
|
|
4
|
+
//#region src/workload-postgres.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* What the stream uses of a WebSocket: the WHATWG API's, which Node's,
|
|
7
|
+
* Deno's, Bun's and the `ws` package's all have; and `pause` and `resume`,
|
|
8
|
+
* which only the `ws` package's has, and which hold back a coffre that does
|
|
9
|
+
* not pace while the app reads nothing.
|
|
10
|
+
*/
|
|
11
|
+
export type TunnelSocket = {
|
|
12
|
+
binaryType: string;
|
|
13
|
+
readonly readyState: number;
|
|
14
|
+
readonly bufferedAmount: number;
|
|
15
|
+
send(data: Uint8Array | string): void;
|
|
16
|
+
close(): void;
|
|
17
|
+
addEventListener(type: 'open' | 'close' | 'error' | 'message', listener: (event: object) => void): void;
|
|
18
|
+
pause?(): void;
|
|
19
|
+
resume?(): void;
|
|
20
|
+
/** The `ws` package's: ends the connection at once, a paused one included, which reads no closing handshake. */
|
|
21
|
+
terminate?(): void;
|
|
22
|
+
};
|
|
23
|
+
/** A WebSocket class that takes the upgrade's headers, as all of those do. */
|
|
24
|
+
export type WebSocketClass = new (url: string, options: {
|
|
25
|
+
headers: Record<string, string>;
|
|
26
|
+
}) => TunnelSocket;
|
|
27
|
+
/**
|
|
28
|
+
* A stream to the database behind the tunnel `name`, which node-postgres
|
|
29
|
+
* connects, writes and ends as it would a socket.
|
|
30
|
+
*/
|
|
31
|
+
export declare function connect(coffre: Workload, name: string, options?: {
|
|
32
|
+
WebSocket?: WebSocketClass;
|
|
33
|
+
}): TunnelStream;
|
|
34
|
+
/**
|
|
35
|
+
* The WebSocket URL of the tunnel `name`: always under its environment,
|
|
36
|
+
* `/use/<project>/<env>/<name>`, which coffre's tunnel route requires,
|
|
37
|
+
* where `url(name)` shortens a single place's to `/use/<name>`.
|
|
38
|
+
*/
|
|
39
|
+
export declare function tunnelUrl(coffre: Workload, name: string): string;
|
|
40
|
+
export declare class TunnelStream extends Duplex {
|
|
41
|
+
#private;
|
|
42
|
+
constructor(coffre: Workload, url: string, WebSocketImpl: WebSocketClass);
|
|
43
|
+
/** node-postgres connects its stream itself; this one is connecting already, and says so with `connect`. */
|
|
44
|
+
connect(): this;
|
|
45
|
+
setNoDelay(): this;
|
|
46
|
+
setKeepAlive(): this;
|
|
47
|
+
ref(): this;
|
|
48
|
+
unref(): this;
|
|
49
|
+
_read(): void;
|
|
50
|
+
_write(chunk: Buffer, _encoding: BufferEncoding, callback: (error?: Error | null) => void): void;
|
|
51
|
+
_final(callback: (error?: Error | null) => void): void;
|
|
52
|
+
_destroy(error: Error | null, callback: (error?: Error | null) => void): void;
|
|
53
|
+
}
|
|
54
|
+
//#endregion
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import { n as upgradeHeaders, r as upgradeRefused } from "./workload-w4QPSyjj.js";
|
|
2
|
+
import { Buffer } from "node:buffer";
|
|
3
|
+
import { Duplex } from "node:stream";
|
|
4
|
+
//#region src/workload-postgres.ts
|
|
5
|
+
/**
|
|
6
|
+
* Postgres from a workload, through coffre's tunnel (docs/design/workload-access.md,
|
|
7
|
+
* section 9.1): a stream node-postgres takes as its socket, carried over the
|
|
8
|
+
* tunnel's WebSocket and signed by the session. No listener, no password,
|
|
9
|
+
* and no database URL in the app: coffre logs in to the database.
|
|
10
|
+
*
|
|
11
|
+
* import pg from 'pg';
|
|
12
|
+
* import { connect } from '@coffre/client/workload/postgres';
|
|
13
|
+
*
|
|
14
|
+
* const pool = new pg.Pool({ stream: () => connect(coffre, 'db') });
|
|
15
|
+
*
|
|
16
|
+
* The WebSocket is the runtime's own (`globalThis.WebSocket`: Node 22 and
|
|
17
|
+
* later, Deno, Bun), which takes the upgrade's headers; on Node 20, pass the
|
|
18
|
+
* `ws` package's: `connect(coffre, 'db', { WebSocket })`.
|
|
19
|
+
*
|
|
20
|
+
* The bytes go by credit, as `coffre run`'s listener sends them
|
|
21
|
+
* (packages/cli/src/tunnels.ts): each side counts back what it took, in
|
|
22
|
+
* text messages, and sends at most a window the other has not counted, so a
|
|
23
|
+
* large result waits in coffre's Durable Object no more than a window. A
|
|
24
|
+
* coffre on Node says so with a byte before any count, and paces nothing.
|
|
25
|
+
*/
|
|
26
|
+
const FLOW = "coffre-tunnel-flow";
|
|
27
|
+
/** What either side may send that the other has not counted back. */
|
|
28
|
+
const WINDOW = 1048576;
|
|
29
|
+
/** How much the app takes before the stream counts it back: well under the window. */
|
|
30
|
+
const COUNT_EVERY = 131072;
|
|
31
|
+
/** How much the stream sends before it waits for the WebSocket to send it: a few COPY chunks. */
|
|
32
|
+
const HIGH_WATER = 1048576;
|
|
33
|
+
/** The most one message carries: a large query is sent in frames, each within the credit left. */
|
|
34
|
+
const FRAME = 65536;
|
|
35
|
+
/** How often an open connection says it is there, so that an idle one outlives Cloudflare's 100-second timeout. */
|
|
36
|
+
const KEEPALIVE_MS = 3e4;
|
|
37
|
+
/**
|
|
38
|
+
* A stream to the database behind the tunnel `name`, which node-postgres
|
|
39
|
+
* connects, writes and ends as it would a socket.
|
|
40
|
+
*/
|
|
41
|
+
function connect(coffre, name, options = {}) {
|
|
42
|
+
const WebSocketImpl = options.WebSocket ?? globalThis.WebSocket;
|
|
43
|
+
if (WebSocketImpl === void 0) throw new Error("this runtime has no WebSocket of its own (Node 20): connect(coffre, name, { WebSocket }) with the ws package's");
|
|
44
|
+
return new TunnelStream(coffre, tunnelUrl(coffre, name), WebSocketImpl);
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* The WebSocket URL of the tunnel `name`: always under its environment,
|
|
48
|
+
* `/use/<project>/<env>/<name>`, which coffre's tunnel route requires,
|
|
49
|
+
* where `url(name)` shortens a single place's to `/use/<name>`.
|
|
50
|
+
*/
|
|
51
|
+
function tunnelUrl(coffre, name) {
|
|
52
|
+
const url = new URL(coffre.url(name));
|
|
53
|
+
if (coffre.places.length === 1) url.pathname = `/use/${[...coffre.places[0].split("/"), name].map(encodeURIComponent).join("/")}`;
|
|
54
|
+
return url.href.replace(/^http/, "ws");
|
|
55
|
+
}
|
|
56
|
+
var TunnelStream = class extends Duplex {
|
|
57
|
+
#ws = null;
|
|
58
|
+
/** Whether coffre paces: unknown until its first message says. */
|
|
59
|
+
#pacing = null;
|
|
60
|
+
/** Bytes sent that coffre has not counted; bytes the app took that this has not counted back; bytes coffre sent that it has not. */
|
|
61
|
+
#uncounted = 0;
|
|
62
|
+
#taken = 0;
|
|
63
|
+
#owed = 0;
|
|
64
|
+
/** Bytes pushed while the app was not reading: counted back once it reads, so coffre waits for it. */
|
|
65
|
+
#held = 0;
|
|
66
|
+
/** A write waiting for room: credit from coffre, or the WebSocket's own buffer to empty. */
|
|
67
|
+
#waiting = null;
|
|
68
|
+
#keepalive;
|
|
69
|
+
/** Whether coffre took the upgrade. */
|
|
70
|
+
#opened = false;
|
|
71
|
+
constructor(coffre, url, WebSocketImpl) {
|
|
72
|
+
super();
|
|
73
|
+
upgradeHeaders(coffre, url).then((headers) => {
|
|
74
|
+
if (this.destroyed || this.writableEnded) return void (this.destroyed || this.destroy());
|
|
75
|
+
const ws = new WebSocketImpl(url, { headers: {
|
|
76
|
+
...headers,
|
|
77
|
+
[FLOW]: "credit"
|
|
78
|
+
} });
|
|
79
|
+
ws.binaryType = "arraybuffer";
|
|
80
|
+
this.#ws = ws;
|
|
81
|
+
ws.addEventListener("open", () => {
|
|
82
|
+
this.#opened = true;
|
|
83
|
+
this.emit("connect");
|
|
84
|
+
this.emit("ready");
|
|
85
|
+
this.#keepalive = setInterval(() => this.#count(), KEEPALIVE_MS);
|
|
86
|
+
this.#keepalive.unref?.();
|
|
87
|
+
this.#release();
|
|
88
|
+
});
|
|
89
|
+
ws.addEventListener("message", (event) => this.#message(event.data));
|
|
90
|
+
ws.addEventListener("close", () => {
|
|
91
|
+
clearInterval(this.#keepalive);
|
|
92
|
+
this.push(null);
|
|
93
|
+
this.destroy();
|
|
94
|
+
});
|
|
95
|
+
ws.addEventListener("error", () => {
|
|
96
|
+
if (ws.readyState !== 1 && !this.#opened) upgradeRefused(coffre);
|
|
97
|
+
this.destroy(/* @__PURE__ */ new Error(`the tunnel to ${url} was refused or cut`));
|
|
98
|
+
});
|
|
99
|
+
}, (error) => this.destroy(error));
|
|
100
|
+
}
|
|
101
|
+
/** node-postgres connects its stream itself; this one is connecting already, and says so with `connect`. */
|
|
102
|
+
connect() {
|
|
103
|
+
return this;
|
|
104
|
+
}
|
|
105
|
+
setNoDelay() {
|
|
106
|
+
return this;
|
|
107
|
+
}
|
|
108
|
+
setKeepAlive() {
|
|
109
|
+
return this;
|
|
110
|
+
}
|
|
111
|
+
ref() {
|
|
112
|
+
return this;
|
|
113
|
+
}
|
|
114
|
+
unref() {
|
|
115
|
+
return this;
|
|
116
|
+
}
|
|
117
|
+
#open() {
|
|
118
|
+
return this.#ws !== null && this.#ws.readyState === 1;
|
|
119
|
+
}
|
|
120
|
+
#full() {
|
|
121
|
+
return !this.#open() || this.#ws.bufferedAmount >= HIGH_WATER || this.#pacing !== false && this.#uncounted >= WINDOW;
|
|
122
|
+
}
|
|
123
|
+
/** Let a waiting write go, once there is room: the WebSocket's own buffer is polled, as it has no event for emptying. */
|
|
124
|
+
#release() {
|
|
125
|
+
if (this.#waiting === null) return;
|
|
126
|
+
if (!this.#full()) {
|
|
127
|
+
const go = this.#waiting;
|
|
128
|
+
this.#waiting = null;
|
|
129
|
+
go();
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
if (this.#open() && this.#ws.bufferedAmount >= HIGH_WATER) setTimeout(() => this.#release(), 10);
|
|
133
|
+
}
|
|
134
|
+
#count() {
|
|
135
|
+
if (!this.#open()) return;
|
|
136
|
+
this.#ws.send(String(this.#taken));
|
|
137
|
+
this.#owed -= this.#taken;
|
|
138
|
+
this.#taken = 0;
|
|
139
|
+
}
|
|
140
|
+
#message(data) {
|
|
141
|
+
if (typeof data === "string") {
|
|
142
|
+
const counted = Number(data);
|
|
143
|
+
if (this.#pacing === false || !/^\d{1,10}$/.test(data) || counted > this.#uncounted) {
|
|
144
|
+
this.destroy(/* @__PURE__ */ new Error("the tunnel broke its flow"));
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
this.#pacing = true;
|
|
148
|
+
this.#uncounted -= counted;
|
|
149
|
+
this.#release();
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
if (this.#pacing === null) {
|
|
153
|
+
this.#pacing = false;
|
|
154
|
+
this.#release();
|
|
155
|
+
}
|
|
156
|
+
this.#owed += data.byteLength;
|
|
157
|
+
if (this.#pacing === true && this.#owed > 2 * WINDOW) {
|
|
158
|
+
this.destroy(/* @__PURE__ */ new Error("the tunnel sent past its window"));
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
if (this.push(Buffer.from(data))) this.#took(data.byteLength);
|
|
162
|
+
else {
|
|
163
|
+
this.#held += data.byteLength;
|
|
164
|
+
if (this.#pacing === false) this.#ws.pause?.();
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
#took(bytes) {
|
|
168
|
+
this.#taken += bytes;
|
|
169
|
+
if (this.#taken >= COUNT_EVERY) this.#count();
|
|
170
|
+
}
|
|
171
|
+
_read() {
|
|
172
|
+
const held = this.#held;
|
|
173
|
+
this.#held = 0;
|
|
174
|
+
if (held > 0) this.#took(held);
|
|
175
|
+
if (this.#pacing === false) this.#ws?.resume?.();
|
|
176
|
+
}
|
|
177
|
+
_write(chunk, _encoding, callback) {
|
|
178
|
+
let offset = 0;
|
|
179
|
+
const next = () => {
|
|
180
|
+
while (offset < chunk.length) {
|
|
181
|
+
if (this.#full()) {
|
|
182
|
+
if (this.#ws !== null && this.#ws.readyState > 1) return callback(/* @__PURE__ */ new Error("the tunnel is closed"));
|
|
183
|
+
this.#waiting = next;
|
|
184
|
+
return this.#release();
|
|
185
|
+
}
|
|
186
|
+
const frame = chunk.subarray(offset, offset + FRAME);
|
|
187
|
+
offset += frame.length;
|
|
188
|
+
this.#uncounted += frame.length;
|
|
189
|
+
this.#ws.send(frame);
|
|
190
|
+
}
|
|
191
|
+
callback();
|
|
192
|
+
};
|
|
193
|
+
next();
|
|
194
|
+
}
|
|
195
|
+
_final(callback) {
|
|
196
|
+
this.#ws?.close();
|
|
197
|
+
callback();
|
|
198
|
+
}
|
|
199
|
+
_destroy(error, callback) {
|
|
200
|
+
clearInterval(this.#keepalive);
|
|
201
|
+
if (this.#ws !== null && this.#ws.readyState <= 1) {
|
|
202
|
+
if (this.#ws.terminate !== void 0) this.#ws.terminate();
|
|
203
|
+
else this.#ws.close();
|
|
204
|
+
}
|
|
205
|
+
this.#waiting = null;
|
|
206
|
+
callback(error);
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
//#endregion
|
|
210
|
+
export { TunnelStream, connect, tunnelUrl };
|