@plurnk/plurnk-contracts 9.0.0 → 10.0.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.
Files changed (81) hide show
  1. package/.env.defaults +1 -19
  2. package/README.md +5 -6
  3. package/SPEC.md +93 -44
  4. package/dist/schema/DaemonNotificationEnvelope.json +77 -30
  5. package/dist/schema/FunctionalityCandidate.json +4 -0
  6. package/dist/schema/FunctionalityDiscoverQuery.json +12 -0
  7. package/dist/schema/FunctionalityDiscoverResult.json +10 -0
  8. package/dist/schema/FunctionalityListQuery.json +33 -0
  9. package/dist/schema/FunctionalityListResult.json +16 -1
  10. package/dist/schema/ModelCatalogPage.json +9 -0
  11. package/dist/schema/PlurnkStatement.json +18 -2
  12. package/dist/schema/ProviderAccounting.json +3 -3
  13. package/dist/schema/ProviderCost.json +1 -1
  14. package/dist/schema/ProviderRequestAccounting.json +3 -3
  15. package/dist/schema/ProviderUsage.json +1 -1
  16. package/dist/src/ActorIdentity.d.ts +26 -0
  17. package/dist/src/ActorIdentity.d.ts.map +1 -0
  18. package/dist/src/ActorIdentity.js +179 -0
  19. package/dist/src/ActorIdentity.js.map +1 -0
  20. package/dist/src/Application.d.ts +38 -126
  21. package/dist/src/Application.d.ts.map +1 -1
  22. package/dist/src/Application.js +47 -220
  23. package/dist/src/Application.js.map +1 -1
  24. package/dist/src/ApplicationNotifications.d.ts +19 -6
  25. package/dist/src/ApplicationNotifications.d.ts.map +1 -1
  26. package/dist/src/ApplicationNotifications.js +6 -3
  27. package/dist/src/ApplicationNotifications.js.map +1 -1
  28. package/dist/src/ApplicationPort.d.ts +27 -6
  29. package/dist/src/ApplicationPort.d.ts.map +1 -1
  30. package/dist/src/ApplicationPort.js +1 -1
  31. package/dist/src/ApplicationPort.js.map +1 -1
  32. package/dist/src/ApplicationStream.d.ts +2 -2
  33. package/dist/src/ApplicationStream.d.ts.map +1 -1
  34. package/dist/src/ApplicationStream.js.map +1 -1
  35. package/dist/src/CollectionCommand.d.ts +33 -0
  36. package/dist/src/CollectionCommand.d.ts.map +1 -0
  37. package/dist/src/CollectionCommand.js +277 -0
  38. package/dist/src/CollectionCommand.js.map +1 -0
  39. package/dist/src/Functionality.d.ts +7 -2
  40. package/dist/src/Functionality.d.ts.map +1 -1
  41. package/dist/src/Functionality.js.map +1 -1
  42. package/dist/src/HttpOrigin.d.ts +79 -10
  43. package/dist/src/HttpOrigin.d.ts.map +1 -1
  44. package/dist/src/HttpOrigin.js +286 -44
  45. package/dist/src/HttpOrigin.js.map +1 -1
  46. package/dist/src/HttpPort.d.ts +35 -0
  47. package/dist/src/HttpPort.d.ts.map +1 -0
  48. package/dist/src/HttpPort.js +106 -0
  49. package/dist/src/HttpPort.js.map +1 -0
  50. package/dist/src/InteractiveCommands.d.ts +96 -0
  51. package/dist/src/InteractiveCommands.d.ts.map +1 -0
  52. package/dist/src/InteractiveCommands.js +409 -0
  53. package/dist/src/InteractiveCommands.js.map +1 -0
  54. package/dist/src/McpWireTool.d.ts +27 -0
  55. package/dist/src/McpWireTool.d.ts.map +1 -0
  56. package/dist/src/McpWireTool.js +30 -0
  57. package/dist/src/McpWireTool.js.map +1 -0
  58. package/dist/src/OAuthClient.d.ts +64 -0
  59. package/dist/src/OAuthClient.d.ts.map +1 -0
  60. package/dist/src/OAuthClient.js +226 -0
  61. package/dist/src/OAuthClient.js.map +1 -0
  62. package/dist/src/ScheduleCommand.d.ts +60 -0
  63. package/dist/src/ScheduleCommand.d.ts.map +1 -0
  64. package/dist/src/ScheduleCommand.js +677 -0
  65. package/dist/src/ScheduleCommand.js.map +1 -0
  66. package/dist/src/SessionProjection.d.ts +91 -0
  67. package/dist/src/SessionProjection.d.ts.map +1 -0
  68. package/dist/src/SessionProjection.js +223 -0
  69. package/dist/src/SessionProjection.js.map +1 -0
  70. package/dist/src/Validator.d.ts +2 -1
  71. package/dist/src/Validator.d.ts.map +1 -1
  72. package/dist/src/Validator.js +19 -1
  73. package/dist/src/Validator.js.map +1 -1
  74. package/dist/src/index.d.ts +10 -3
  75. package/dist/src/index.d.ts.map +1 -1
  76. package/dist/src/index.js +7 -1
  77. package/dist/src/index.js.map +1 -1
  78. package/dist/src/types.generated.d.ts +85 -21
  79. package/dist/src/types.generated.d.ts.map +1 -1
  80. package/dist/src/types.generated.js.map +1 -1
  81. package/package.json +3 -2
@@ -1,29 +1,279 @@
1
1
  import Problems from "./Problems.js";
2
+ const firstHeader = (raw) => typeof raw === "string" ? raw : Array.isArray(raw) ? raw[0] : undefined;
3
+ /**
4
+ * {§http-admission} Recognizes IPv4/IPv6 loopback hostnames and IPv4-mapped IPv6 loopback addresses.
5
+ */
6
+ export const isLoopbackHost = (hostname) => {
7
+ if (typeof hostname !== "string" || hostname.length === 0)
8
+ return false;
9
+ const lower = hostname.toLowerCase();
10
+ return (lower === "127.0.0.1"
11
+ || lower === "localhost"
12
+ || lower === "::1"
13
+ || lower === "[::1]"
14
+ || lower === "::ffff:127.0.0.1"
15
+ || lower === "[::ffff:127.0.0.1]");
16
+ };
17
+ const isWildcardBindHost = (host) => host === "0.0.0.0" || host === "::" || host === "[::]";
18
+ const formatHostPort = (host, port) => `${host.includes(":") && !host.startsWith("[") ? `[${host}]` : host}:${port}`;
2
19
  /**
3
20
  * {§http-host} The origin a request reached this daemon at: the address its `Host` names,
4
21
  * over http, or the listener's own for a request that names none.
5
22
  */
6
23
  export const requestOrigin = (req, listener) => {
7
- const named = req.headers.host;
8
- if (typeof named === "string" && named.length > 0) {
24
+ const named = firstHeader(req.headers.host);
25
+ if (named !== undefined && named.length > 0) {
9
26
  try {
10
27
  return `http://${new URL(`http://${named}`).host}`;
11
28
  }
12
29
  catch { /* a Host that is no address names nothing */ }
13
30
  }
14
- return `http://${listener.host.includes(":") ? `[${listener.host}]` : listener.host}:${listener.port}`;
31
+ return `http://${formatHostPort(listener.host, listener.port)}`;
32
+ };
33
+ /**
34
+ * {§http-admission} {§http-host} Resolves the daemon's public HTTP(S) origin for a request:
35
+ * 1. Honors an explicit public issuer configured on `CredentialAuthority` (`https://` or static custom origin).
36
+ * 2. Honors `X-Forwarded-Proto` / `X-Forwarded-Host` when delivered over a loopback reverse proxy.
37
+ * 3. Falls back to the request `Host` header or normalized listener address (`0.0.0.0` / `::` -> `127.0.0.1`).
38
+ */
39
+ export const resolvePublicOrigin = (req, listener, credentials) => {
40
+ const rawHost = typeof listener.host === "string" ? listener.host : "";
41
+ const hasPort = typeof listener.port === "number";
42
+ const rawListenerOrigin = rawHost.length > 0 && hasPort ? `http://${formatHostPort(rawHost, listener.port)}` : "";
43
+ const defaultHost = rawHost.length === 0 ? "" : isWildcardBindHost(rawHost) ? "127.0.0.1" : rawHost;
44
+ const defaultListenerOrigin = defaultHost.length > 0 && hasPort ? `http://${formatHostPort(defaultHost, listener.port)}` : "";
45
+ const face = credentials?.face() ?? null;
46
+ if (face !== null) {
47
+ const unconfigured = face.issuer().trim();
48
+ const candidate = (req !== undefined ? face.issuer(req) : unconfigured).trim();
49
+ if (candidate.length > 0) {
50
+ try {
51
+ const parsed = new URL(candidate);
52
+ const isExplicitStaticIssuer = unconfigured.length > 0
53
+ && unconfigured === candidate
54
+ && unconfigured !== rawListenerOrigin
55
+ && unconfigured !== defaultListenerOrigin;
56
+ if ((parsed.protocol === "https:" || parsed.protocol === "http:")
57
+ && (parsed.protocol === "https:" || isExplicitStaticIssuer)) {
58
+ return parsed.origin;
59
+ }
60
+ }
61
+ catch {
62
+ // Fall back to request/listener resolution when configured issuer is malformed.
63
+ }
64
+ }
65
+ }
66
+ const remoteAddress = req?.socket?.remoteAddress;
67
+ const localAddress = req?.socket?.localAddress;
68
+ const onLoopbackSocket = (remoteAddress === undefined ? isLoopbackHost(rawHost) : isLoopbackHost(remoteAddress))
69
+ && (isLoopbackHost(rawHost) || (isWildcardBindHost(rawHost) && isLoopbackHost(localAddress)));
70
+ const forwardedProto = firstHeader(req?.headers["x-forwarded-proto"])?.split(",", 1)[0]?.trim().toLowerCase();
71
+ const scheme = onLoopbackSocket && (forwardedProto === "https" || forwardedProto === "http")
72
+ ? forwardedProto
73
+ : "http";
74
+ const forwardedHost = onLoopbackSocket && (forwardedProto === "https" || forwardedProto === "http")
75
+ ? firstHeader(req?.headers["x-forwarded-host"])?.split(",", 1)[0]?.trim()
76
+ : undefined;
77
+ const rawHeader = forwardedHost !== undefined && forwardedHost.length > 0
78
+ ? forwardedHost
79
+ : firstHeader(req?.headers.host)?.trim() ?? "";
80
+ if (rawHeader.length > 0) {
81
+ try {
82
+ const parsed = new URL(`${scheme}://${rawHeader}`);
83
+ if (parsed.username === ""
84
+ && parsed.password === ""
85
+ && parsed.pathname === "/"
86
+ && parsed.search === ""
87
+ && parsed.hash === ""
88
+ && !isWildcardBindHost(parsed.hostname)) {
89
+ if (scheme === "https"
90
+ || parsed.port.length > 0
91
+ || rawHeader.endsWith(":80")
92
+ || !hasPort) {
93
+ return parsed.origin;
94
+ }
95
+ return `http://${formatHostPort(parsed.hostname, listener.port)}`;
96
+ }
97
+ }
98
+ catch {
99
+ // Fall back to listener address when Host header is malformed.
100
+ }
101
+ }
102
+ if (defaultListenerOrigin.length > 0) {
103
+ return scheme === "https" && defaultHost.length > 0 && hasPort
104
+ ? `https://${formatHostPort(defaultHost, listener.port)}`
105
+ : defaultListenerOrigin;
106
+ }
107
+ return "";
15
108
  };
16
109
  /**
17
- * {§credential-authority} {§http-host} Verifies an HTTP request against the daemon's
18
- * `CredentialAuthority` using `Authorization: Bearer <token>` (or `?access_token=<token>` when
19
- * `allowQueryToken` is set for SSE/WebSocket entry points), returning the admitted credential's
20
- * family/subject or an RFC 9457 Problem and RFC 6750 / RFC 9728 `WWW-Authenticate` challenge.
110
+ * {§http-admission} Builds lowercase CORS response headers when `allowOrigin` is non-empty;
111
+ * returns an empty object under the same-origin default (`allowOrigin === ""`).
21
112
  */
22
- export const admitBearerRequest = (credentials, req, options = {}) => {
113
+ export const buildCorsHeaders = (allowOrigin, options) => {
114
+ const origin = allowOrigin.trim();
115
+ if (origin.length === 0)
116
+ return {};
117
+ const requested = firstHeader(options.requestHeaders)?.trim();
118
+ const allowHeaders = requested !== undefined && requested.length > 0 && options.allowHeaders === "*"
119
+ ? requested
120
+ : options.allowHeaders;
121
+ return {
122
+ "access-control-allow-origin": origin,
123
+ "access-control-allow-methods": options.methods,
124
+ "access-control-allow-headers": allowHeaders,
125
+ ...(options.exposeHeaders !== undefined && options.exposeHeaders.length > 0
126
+ ? { "access-control-expose-headers": options.exposeHeaders }
127
+ : {}),
128
+ };
129
+ };
130
+ /**
131
+ * {§http-admission} Parses `/<mount>[/<workspace>[/<session>]]` pathnames with URI-component decoding
132
+ * and RFC 9457 Problem refusals on out-of-scope routes (`404`) or malformed percent-encoding (`400`).
133
+ */
134
+ export const parseScopedRoute = (pathname, options) => {
135
+ const mount = options.mount.endsWith("/") && options.mount.length > 1
136
+ ? options.mount.slice(0, -1)
137
+ : options.mount;
138
+ const problem = (slug, status, detail, extra = {}) => Problems.create(options.domain, slug, status, detail, {
139
+ ...(options.codePrefix === undefined ? {} : { code: `${options.codePrefix}/${slug}` }),
140
+ path: pathname,
141
+ stage: "routing",
142
+ retryable: false,
143
+ ...extra,
144
+ });
145
+ if (pathname === mount || pathname === `${mount}/`) {
146
+ return { ok: true };
147
+ }
148
+ const prefix = `${mount}/`;
149
+ if (!pathname.startsWith(prefix)) {
150
+ return {
151
+ ok: false,
152
+ problem: problem("route-not-found", 404, options.notFoundDetail ?? "The requested HTTP route does not exist."),
153
+ };
154
+ }
155
+ const trimmed = pathname.endsWith("/") ? pathname.slice(prefix.length, -1) : pathname.slice(prefix.length);
156
+ const rawParts = trimmed.split("/");
157
+ if (rawParts.length > 2 || rawParts.some((part) => part.length === 0)) {
158
+ return {
159
+ ok: false,
160
+ problem: problem("route-not-found", 404, options.notFoundDetail ?? "The requested HTTP route does not exist.", {
161
+ recovery: `Use \`${mount}\`, \`${mount}/<workspace>\`, or \`${mount}/<workspace>/<session>\`.`,
162
+ }),
163
+ };
164
+ }
165
+ try {
166
+ const decoded = rawParts.map((part) => decodeURIComponent(part));
167
+ if (options.emptySegmentDetail !== undefined && decoded.some((part) => part.trim().length === 0)) {
168
+ return {
169
+ ok: false,
170
+ problem: problem("request-target-invalid", 400, options.emptySegmentDetail),
171
+ };
172
+ }
173
+ return {
174
+ ok: true,
175
+ workspaceSegment: decoded[0],
176
+ sessionSegment: decoded[1],
177
+ };
178
+ }
179
+ catch {
180
+ return {
181
+ ok: false,
182
+ problem: problem("request-target-invalid", 400, options.malformedEncodingDetail ?? `The ${mount} route contains malformed percent-encoding.`),
183
+ };
184
+ }
185
+ };
186
+ /**
187
+ * {§http-host} {§http-admission} Enforces browser same-origin CSRF / Cross-Site WebSocket Hijacking protection
188
+ * (`Sec-Fetch-Site` and `Origin` matching the target `Host`) when `allowOrigin` is empty, and
189
+ * rejects browser DNS-rebinding `Host` headers on direct unproxied loopback listeners. Non-browser
190
+ * clients (carrying neither `Origin` nor `Sec-Fetch-*`) pass through untouched.
191
+ */
192
+ export const admitBrowserOrigin = (req, options) => {
193
+ const domain = options.domain ?? "daemon:http";
194
+ const codePrefix = options.codePrefix;
195
+ const reject = (slug, detail) => ({
196
+ ok: false,
197
+ problem: Problems.create(domain, slug, 403, detail, {
198
+ ...(codePrefix === undefined ? {} : { code: `${codePrefix}/${slug}` }),
199
+ stage: "authorization",
200
+ retryable: false,
201
+ }),
202
+ });
203
+ const allowOrigin = options.allowOrigin.trim();
204
+ const rawOrigin = firstHeader(req.headers.origin)?.trim();
205
+ const rawFetchSite = firstHeader(req.headers["sec-fetch-site"])?.trim().toLowerCase();
206
+ const rawFetchMode = firstHeader(req.headers["sec-fetch-mode"])?.trim().toLowerCase();
207
+ const isBrowserRequest = rawOrigin !== undefined || rawFetchSite !== undefined || rawFetchMode !== undefined;
208
+ if (!isBrowserRequest)
209
+ return { ok: true };
210
+ if (allowOrigin === "*")
211
+ return { ok: true };
212
+ if (allowOrigin.length > 0) {
213
+ if (rawOrigin !== undefined && rawOrigin !== allowOrigin) {
214
+ return reject("cross-origin-forbidden", "The browser Origin header does not match the configured allowed origin.");
215
+ }
216
+ return { ok: true };
217
+ }
218
+ const hasForwarded = firstHeader(req.headers["x-forwarded-for"]) !== undefined ||
219
+ firstHeader(req.headers["x-forwarded-proto"]) !== undefined ||
220
+ firstHeader(req.headers["x-forwarded-host"]) !== undefined ||
221
+ firstHeader(req.headers.forwarded) !== undefined;
222
+ const rawHostHeader = (firstHeader(req.headers["x-forwarded-host"])?.split(",", 1)[0]?.trim() || firstHeader(req.headers.host)?.trim()) ?? "";
223
+ if (isLoopbackHost(options.listener.host) && !hasForwarded && rawHostHeader.length > 0) {
224
+ try {
225
+ const parsedHost = new URL(`http://${rawHostHeader}`);
226
+ if (!isLoopbackHost(parsedHost.hostname)) {
227
+ return reject("host-not-allowed", "Browser requests to a loopback listener must target a loopback Host.");
228
+ }
229
+ }
230
+ catch {
231
+ return reject("host-not-allowed", "The request Host header is malformed.");
232
+ }
233
+ }
234
+ if (rawFetchSite !== undefined && rawFetchSite !== "same-origin" && rawFetchSite !== "none") {
235
+ return reject("cross-origin-forbidden", "Cross-origin browser requests are not permitted.");
236
+ }
237
+ if (rawOrigin !== undefined) {
238
+ if (rawOrigin === "null" || rawHostHeader.length === 0) {
239
+ return reject("cross-origin-forbidden", "The browser Origin header must match the target Host.");
240
+ }
241
+ try {
242
+ const originUrl = new URL(rawOrigin);
243
+ const expectedUrl = new URL(`${originUrl.protocol}//${rawHostHeader}`);
244
+ if (originUrl.host.toLowerCase() !== expectedUrl.host.toLowerCase()) {
245
+ return reject("cross-origin-forbidden", "The browser Origin header must match the target Host.");
246
+ }
247
+ }
248
+ catch {
249
+ return reject("cross-origin-forbidden", "The browser Origin header is malformed.");
250
+ }
251
+ }
252
+ return { ok: true };
253
+ };
254
+ const extractWsProtocolBearer = (rawProtocol) => {
255
+ const joined = typeof rawProtocol === "string" ? rawProtocol : Array.isArray(rawProtocol) ? rawProtocol.join(",") : "";
256
+ if (joined.length === 0)
257
+ return null;
258
+ for (const part of joined.split(",")) {
259
+ const trimmed = part.trim();
260
+ if (trimmed.startsWith("bearer.") && trimmed.length > "bearer.".length) {
261
+ return trimmed.slice("bearer.".length);
262
+ }
263
+ }
264
+ return null;
265
+ };
266
+ /**
267
+ * {§credential-authority} {§http-host} {§http-admission} Verifies an HTTP/WebSocket request against the daemon's
268
+ * `CredentialAuthority` using `Authorization: Bearer <token>` (or `Sec-WebSocket-Protocol: bearer.<token>` /
269
+ * `?access_token=<token>` when `allowQueryToken` is set), returning the admitted principal `subject`
270
+ * or an RFC 9457 Problem and RFC 6750 / RFC 9728 `WWW-Authenticate` challenge.
271
+ */
272
+ export const admitBearerRequest = async (credentials, req, options = {}) => {
23
273
  const face = credentials.face();
24
- const issuer = face?.issuer(req);
25
- if (face === null || issuer === undefined) {
26
- return { ok: true, family: null, subject: null };
274
+ const resourceOrigin = face?.issuer(req);
275
+ if (face === null || resourceOrigin === undefined) {
276
+ return { ok: true, subject: null };
27
277
  }
28
278
  const domain = options.domain ?? "daemon:http";
29
279
  const codePrefix = options.codePrefix;
@@ -31,54 +281,46 @@ export const admitBearerRequest = (credentials, req, options = {}) => {
31
281
  ...(codePrefix === undefined ? {} : { code: `${codePrefix}/${slug}` }),
32
282
  ...fields,
33
283
  });
34
- const rawHeader = req.headers.authorization;
35
- const header = typeof rawHeader === "string" ? rawHeader : undefined;
36
- const challenge = (parameters) => `Bearer realm="plurnk"${parameters}, resource_metadata="${issuer}/.well-known/oauth-protected-resource"`;
37
- let presented = header === undefined ? null : /^Bearer(?:\s+(.*))?$/iu.exec(header);
38
- if (presented === null && options.allowQueryToken === true) {
39
- const url = new URL(req.url ?? "/", "http://listener");
40
- const queryToken = url.searchParams.get("access_token");
41
- if (queryToken !== null)
42
- presented = /^Bearer(?:\s+(.*))?$/iu.exec(`Bearer ${queryToken}`);
43
- }
44
- if (presented === null) {
284
+ const header = firstHeader(req.headers.authorization);
285
+ const challenge = (parameters) => `Bearer realm="plurnk"${parameters}, resource_metadata="${resourceOrigin}/.well-known/oauth-protected-resource"`;
286
+ let token = null;
287
+ if (header !== undefined) {
288
+ const match = /^Bearer(?:\s+(.*))?$/iu.exec(header);
289
+ if (match !== null)
290
+ token = (match[1] ?? "").trim();
291
+ }
292
+ if (token === null && options.allowQueryToken === true) {
293
+ token = extractWsProtocolBearer(req.headers["sec-websocket-protocol"]);
294
+ if (token === null) {
295
+ const url = new URL(req.url ?? "/", "http://listener");
296
+ const queryToken = url.searchParams.get("access_token");
297
+ if (queryToken !== null)
298
+ token = queryToken.trim();
299
+ }
300
+ }
301
+ if (token === null) {
45
302
  return {
46
303
  ok: false,
47
304
  challenge: challenge(""),
48
305
  problem: problem("bearer-token-required", 401, "The request did not provide a bearer token.", {
49
306
  stage: "authorization",
50
- recovery: "Present an access token issued by this daemon as `Authorization: Bearer <token>`.",
51
- retryable: false,
52
- }),
53
- };
54
- }
55
- const token = (presented[1] ?? "").trim();
56
- const claims = credentials.verify(token);
57
- if (claims === null || claims.kind !== "access") {
58
- return {
59
- ok: false,
60
- challenge: challenge(', error="invalid_token", error_description="The access token is unknown, expired or revoked."'),
61
- problem: problem("bearer-token-invalid", 401, "The access token is unknown, expired or revoked.", {
62
- stage: "authorization",
63
- recovery: "Obtain a new access token from this daemon's token endpoint.",
307
+ recovery: "Present a valid OIDC bearer token as `Authorization: Bearer <token>`.",
64
308
  retryable: false,
65
309
  }),
66
310
  };
67
311
  }
68
- const requiredScope = options.requiredScope ?? "acp";
69
- const acceptedScopes = options.acceptedScopes ?? [requiredScope];
70
- if (!acceptedScopes.some((scope) => claims.scopes.includes(scope))) {
312
+ const claims = token.length === 0 ? null : await credentials.verify(token);
313
+ if (claims === null) {
71
314
  return {
72
315
  ok: false,
73
- challenge: challenge(`, error="insufficient_scope", scope="${requiredScope}"`),
74
- problem: problem("bearer-scope-insufficient", 403, `The access token does not carry the scope ${requiredScope}.`, {
316
+ challenge: challenge(', error="invalid_token", error_description="The bearer token is invalid, expired, or not authorized for this resource."'),
317
+ problem: problem("bearer-token-invalid", 401, "The bearer token is invalid, expired, or not authorized for this resource.", {
75
318
  stage: "authorization",
76
- scope: requiredScope,
77
- recovery: `Obtain an access token with the scope ${requiredScope}.`,
319
+ recovery: "Obtain a valid access token from the authorization server advertised in `/.well-known/oauth-protected-resource`.",
78
320
  retryable: false,
79
321
  }),
80
322
  };
81
323
  }
82
- return { ok: true, family: claims.family, subject: claims.subject };
324
+ return { ok: true, subject: claims.subject };
83
325
  };
84
326
  //# sourceMappingURL=HttpOrigin.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"HttpOrigin.js","sourceRoot":"","sources":["../../src/HttpOrigin.ts"],"names":[],"mappings":"AACA,OAAO,QAAQ,MAAM,eAAe,CAAC;AAWrC;;;GAGG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,GAAmB,EAAE,QAA0D,EAAU,EAAE;IACrH,MAAM,KAAK,GAAG,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC;IAC/B,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAChD,IAAI,CAAC;YAAC,OAAO,UAAU,IAAI,GAAG,CAAC,UAAU,KAAK,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;QAAC,CAAC;QAAC,MAAM,CAAC,CAAC,6CAA6C,CAAC,CAAC;IACvH,CAAC;IACD,OAAO,UAAU,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,QAAQ,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,IAAI,QAAQ,CAAC,IAAI,EAAE,CAAC;AAC3G,CAAC,CAAC;AAcF;;;;;GAKG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAC9B,WAAgC,EAChC,GAA2D,EAC3D,OAAO,GAA2B,EAAE,EACrB,EAAE;IACjB,MAAM,IAAI,GAAG,WAAW,CAAC,IAAI,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EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC;QACjE,OAAO;YACH,EAAE,EAAE,KAAK;YACT,SAAS,EAAE,SAAS,CAAC,wCAAwC,aAAa,GAAG,CAAC;YAC9E,OAAO,EAAE,OAAO,CACZ,2BAA2B,EAC3B,GAAG,EACH,6CAA6C,aAAa,GAAG,EAC7D;gBACI,KAAK,EAAE,eAAe;gBACtB,KAAK,EAAE,aAAa;gBACpB,QAAQ,EAAE,yCAAyC,aAAa,GAAG;gBACnE,SAAS,EAAE,KAAK;aACnB,CACJ;SACJ,CAAC;IACN,CAAC;IACD,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,CAAC;AACxE,CAAC,CAAC","sourcesContent":["import type { CredentialAuthority } from \"./Application.ts\";\nimport Problems from \"./Problems.ts\";\nimport type { ProblemDetails } from \"./types.generated.ts\";\n\n/**\n * {§http-host} A request as far as its headers, which is all an origin is read from. A Node request\n * satisfies it, and naming it keeps the package root runtime-neutral ({§whitespace-contract}).\n */\nexport interface RequestHeaders {\n readonly headers: Readonly<Record<string, string | readonly string[] | undefined>>;\n}\n\n/**\n * {§http-host} The origin a request reached this daemon at: the address its `Host` names,\n * over http, or the listener's own for a request that names none.\n */\nexport const requestOrigin = (req: RequestHeaders, listener: { readonly host: string; readonly port: number }): string => {\n const named = req.headers.host;\n if (typeof named === \"string\" && named.length > 0) {\n try { return `http://${new URL(`http://${named}`).host}`; } catch { /* a Host that is no address names nothing */ }\n }\n return `http://${listener.host.includes(\":\") ? `[${listener.host}]` : listener.host}:${listener.port}`;\n};\n\nexport interface BearerAdmissionOptions {\n readonly allowQueryToken?: boolean;\n readonly domain?: string;\n readonly codePrefix?: string;\n readonly requiredScope?: string;\n readonly acceptedScopes?: readonly string[];\n}\n\nexport type BearerAdmission =\n | { readonly ok: true; readonly family: string | null; readonly subject: string | null }\n | { readonly ok: false; readonly problem: ProblemDetails; readonly challenge: string };\n\n/**\n * {§credential-authority} {§http-host} Verifies an HTTP request against the daemon's\n * `CredentialAuthority` using `Authorization: Bearer <token>` (or `?access_token=<token>` when\n * `allowQueryToken` is set for SSE/WebSocket entry points), returning the admitted credential's\n * family/subject or an RFC 9457 Problem and RFC 6750 / RFC 9728 `WWW-Authenticate` challenge.\n */\nexport const admitBearerRequest = (\n credentials: CredentialAuthority,\n req: RequestHeaders & { readonly url?: string | undefined },\n options: BearerAdmissionOptions = {},\n): BearerAdmission => {\n const face = credentials.face();\n const issuer = face?.issuer(req);\n if (face === null || issuer === undefined) {\n return { ok: true, family: null, subject: null };\n }\n\n const domain = options.domain ?? \"daemon:http\";\n const codePrefix = options.codePrefix;\n const problem = (slug: string, status: number, detail: string, fields: Readonly<Record<string, unknown>>): ProblemDetails =>\n Problems.create(domain, slug, status, detail, {\n ...(codePrefix === undefined ? {} : { code: `${codePrefix}/${slug}` }),\n ...fields,\n });\n\n const rawHeader = req.headers.authorization;\n const header = typeof rawHeader === \"string\" ? rawHeader : undefined;\n const challenge = (parameters: string): string =>\n `Bearer realm=\"plurnk\"${parameters}, resource_metadata=\"${issuer}/.well-known/oauth-protected-resource\"`;\n let presented = header === undefined ? null : /^Bearer(?:\\s+(.*))?$/iu.exec(header);\n if (presented === null && options.allowQueryToken === true) {\n const url = new URL(req.url ?? \"/\", \"http://listener\");\n const queryToken = url.searchParams.get(\"access_token\");\n if (queryToken !== null) presented = /^Bearer(?:\\s+(.*))?$/iu.exec(`Bearer ${queryToken}`);\n }\n if (presented === null) {\n return {\n ok: false,\n challenge: challenge(\"\"),\n problem: problem(\"bearer-token-required\", 401, \"The request did not provide a bearer token.\", {\n stage: \"authorization\",\n recovery: \"Present an access token issued by this daemon as `Authorization: Bearer <token>`.\",\n retryable: false,\n }),\n };\n }\n const token = (presented[1] ?? \"\").trim();\n const claims = credentials.verify(token);\n if (claims === null || claims.kind !== \"access\") {\n return {\n ok: false,\n challenge: challenge(\n ', error=\"invalid_token\", error_description=\"The access token is unknown, expired or revoked.\"',\n ),\n problem: problem(\"bearer-token-invalid\", 401, \"The access token is unknown, expired or revoked.\", {\n stage: \"authorization\",\n recovery: \"Obtain a new access token from this daemon's token endpoint.\",\n retryable: false,\n }),\n };\n }\n const requiredScope = options.requiredScope ?? \"acp\";\n const acceptedScopes = options.acceptedScopes ?? [requiredScope];\n if (!acceptedScopes.some((scope) => claims.scopes.includes(scope))) {\n return {\n ok: false,\n challenge: challenge(`, error=\"insufficient_scope\", scope=\"${requiredScope}\"`),\n problem: problem(\n \"bearer-scope-insufficient\",\n 403,\n `The access token does not carry the scope ${requiredScope}.`,\n {\n stage: \"authorization\",\n scope: requiredScope,\n recovery: `Obtain an access token with the scope ${requiredScope}.`,\n retryable: false,\n },\n ),\n };\n }\n return { ok: true, family: claims.family, subject: claims.subject };\n};\n"]}
1
+ {"version":3,"file":"HttpOrigin.js","sourceRoot":"","sources":["../../src/HttpOrigin.ts"],"names":[],"mappings":"AACA,OAAO,QAAQ,MAAM,eAAe,CAAC;AAerC,MAAM,WAAW,GAAG,CAAC,GAA2C,EAAsB,EAAE,CACpF,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;AAE5E;;GAEG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,CAAC,QAA4B,EAAW,EAAE;IACpE,IAAI,OAAO,QAAQ,KAAK,QAAQ,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IACxE,MAAM,KAAK,GAAG,QAAQ,CAAC,WAAW,EAAE,CAAC;IACrC,OAAO,CACH,KAAK,KAAK,WAAW;WAClB,KAAK,KAAK,WAAW;WACrB,KAAK,KAAK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AAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,WAAW,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAC3E,IAAI,MAAM,KAAK,IAAI,EAAE,CAAC;QAClB,OAAO;YACH,EAAE,EAAE,KAAK;YACT,SAAS,EAAE,SAAS,CAChB,yHAAyH,CAC5H;YACD,OAAO,EAAE,OAAO,CAAC,sBAAsB,EAAE,GAAG,EAAE,4EAA4E,EAAE;gBACxH,KAAK,EAAE,eAAe;gBACtB,QAAQ,EAAE,kHAAkH;gBAC5H,SAAS,EAAE,KAAK;aACnB,CAAC;SACL,CAAC;IACN,CAAC;IACD,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,CAAC;AACjD,CAAC,CAAC","sourcesContent":["import type { CredentialAuthority } from \"./Application.ts\";\nimport Problems from \"./Problems.ts\";\nimport type { ProblemDetails } from \"./types.generated.ts\";\n\n/**\n * {§http-host} {§http-admission} A request as far as its headers (and optional socket endpoint),\n * keeping the package root runtime-neutral ({§whitespace-contract}).\n */\nexport interface RequestHeaders {\n readonly headers: Readonly<Record<string, string | readonly string[] | undefined>>;\n readonly socket?: {\n readonly remoteAddress?: string | undefined;\n readonly localAddress?: string | undefined;\n };\n}\n\nconst firstHeader = (raw: string | readonly string[] | undefined): string | undefined =>\n typeof raw === \"string\" ? raw : Array.isArray(raw) ? raw[0] : undefined;\n\n/**\n * {§http-admission} Recognizes IPv4/IPv6 loopback hostnames and IPv4-mapped IPv6 loopback addresses.\n */\nexport const isLoopbackHost = (hostname: string | undefined): boolean => {\n if (typeof hostname !== \"string\" || hostname.length === 0) return false;\n const lower = hostname.toLowerCase();\n return (\n lower === \"127.0.0.1\"\n || lower === \"localhost\"\n || lower === \"::1\"\n || lower === \"[::1]\"\n || lower === \"::ffff:127.0.0.1\"\n || lower === \"[::ffff:127.0.0.1]\"\n );\n};\n\nconst isWildcardBindHost = (host: string): boolean =>\n host === \"0.0.0.0\" || host === \"::\" || host === \"[::]\";\n\nconst formatHostPort = (host: string, port: number): string =>\n `${host.includes(\":\") && !host.startsWith(\"[\") ? `[${host}]` : host}:${port}`;\n\n/**\n * {§http-host} The origin a request reached this daemon at: the address its `Host` names,\n * over http, or the listener's own for a request that names none.\n */\nexport const requestOrigin = (req: RequestHeaders, listener: { readonly host: string; readonly port: number }): string => {\n const named = firstHeader(req.headers.host);\n if (named !== undefined && named.length > 0) {\n try { return `http://${new URL(`http://${named}`).host}`; } catch { /* a Host that is no address names nothing */ }\n }\n return `http://${formatHostPort(listener.host, listener.port)}`;\n};\n\n/**\n * {§http-admission} {§http-host} Resolves the daemon's public HTTP(S) origin for a request:\n * 1. Honors an explicit public issuer configured on `CredentialAuthority` (`https://` or static custom origin).\n * 2. Honors `X-Forwarded-Proto` / `X-Forwarded-Host` when delivered over a loopback reverse proxy.\n * 3. Falls back to the request `Host` header or normalized listener address (`0.0.0.0` / `::` -> `127.0.0.1`).\n */\nexport const resolvePublicOrigin = (\n req: RequestHeaders | undefined,\n listener: { readonly host: string; readonly port: number },\n credentials?: CredentialAuthority | null,\n): string => {\n const rawHost = typeof listener.host === \"string\" ? listener.host : \"\";\n const hasPort = typeof listener.port === \"number\";\n const rawListenerOrigin = rawHost.length > 0 && hasPort ? `http://${formatHostPort(rawHost, listener.port)}` : \"\";\n const defaultHost = rawHost.length === 0 ? \"\" : isWildcardBindHost(rawHost) ? \"127.0.0.1\" : rawHost;\n const defaultListenerOrigin = defaultHost.length > 0 && hasPort ? `http://${formatHostPort(defaultHost, listener.port)}` : \"\";\n\n const face = credentials?.face() ?? null;\n if (face !== null) {\n const unconfigured = face.issuer().trim();\n const candidate = (req !== undefined ? face.issuer(req) : unconfigured).trim();\n if (candidate.length > 0) {\n try {\n const parsed = new URL(candidate);\n const isExplicitStaticIssuer =\n unconfigured.length > 0\n && unconfigured === candidate\n && unconfigured !== rawListenerOrigin\n && unconfigured !== defaultListenerOrigin;\n if (\n (parsed.protocol === \"https:\" || parsed.protocol === \"http:\")\n && (parsed.protocol === \"https:\" || isExplicitStaticIssuer)\n ) {\n return parsed.origin;\n }\n } catch {\n // Fall back to request/listener resolution when configured issuer is malformed.\n }\n }\n }\n\n const remoteAddress = req?.socket?.remoteAddress;\n const localAddress = req?.socket?.localAddress;\n const onLoopbackSocket =\n (remoteAddress === undefined ? isLoopbackHost(rawHost) : isLoopbackHost(remoteAddress))\n && (isLoopbackHost(rawHost) || (isWildcardBindHost(rawHost) && isLoopbackHost(localAddress)));\n\n const forwardedProto = firstHeader(req?.headers[\"x-forwarded-proto\"])?.split(\",\", 1)[0]?.trim().toLowerCase();\n const scheme =\n onLoopbackSocket && (forwardedProto === \"https\" || forwardedProto === \"http\")\n ? forwardedProto\n : \"http\";\n const forwardedHost =\n onLoopbackSocket && (forwardedProto === \"https\" || forwardedProto === \"http\")\n ? firstHeader(req?.headers[\"x-forwarded-host\"])?.split(\",\", 1)[0]?.trim()\n : undefined;\n const rawHeader =\n forwardedHost !== undefined && forwardedHost.length > 0\n ? forwardedHost\n : firstHeader(req?.headers.host)?.trim() ?? \"\";\n\n if (rawHeader.length > 0) {\n try {\n const parsed = new URL(`${scheme}://${rawHeader}`);\n if (\n parsed.username === \"\"\n && parsed.password === \"\"\n && parsed.pathname === \"/\"\n && parsed.search === \"\"\n && parsed.hash === \"\"\n && !isWildcardBindHost(parsed.hostname)\n ) {\n if (\n scheme === \"https\"\n || parsed.port.length > 0\n || rawHeader.endsWith(\":80\")\n || !hasPort\n ) {\n return parsed.origin;\n }\n return `http://${formatHostPort(parsed.hostname, listener.port)}`;\n }\n } catch {\n // Fall back to listener address when Host header is malformed.\n }\n }\n\n if (defaultListenerOrigin.length > 0) {\n return scheme === \"https\" && defaultHost.length > 0 && hasPort\n ? `https://${formatHostPort(defaultHost, listener.port)}`\n : defaultListenerOrigin;\n }\n return \"\";\n};\n\nexport interface CorsHeaderOptions {\n readonly methods: string;\n readonly allowHeaders: string;\n readonly exposeHeaders?: string;\n readonly requestHeaders?: string | readonly string[] | undefined;\n}\n\n/**\n * {§http-admission} Builds lowercase CORS response headers when `allowOrigin` is non-empty;\n * returns an empty object under the same-origin default (`allowOrigin === \"\"`).\n */\nexport const buildCorsHeaders = (\n allowOrigin: string,\n options: CorsHeaderOptions,\n): Record<string, string> => {\n const origin = allowOrigin.trim();\n if (origin.length === 0) return {};\n const requested = firstHeader(options.requestHeaders)?.trim();\n const allowHeaders =\n requested !== undefined && requested.length > 0 && options.allowHeaders === \"*\"\n ? requested\n : options.allowHeaders;\n return {\n \"access-control-allow-origin\": origin,\n \"access-control-allow-methods\": options.methods,\n \"access-control-allow-headers\": allowHeaders,\n ...(options.exposeHeaders !== undefined && options.exposeHeaders.length > 0\n ? { \"access-control-expose-headers\": options.exposeHeaders }\n : {}),\n };\n};\n\nexport interface ScopedRouteOptions {\n readonly mount: string;\n readonly domain: string;\n readonly codePrefix?: string;\n readonly notFoundDetail?: string;\n readonly malformedEncodingDetail?: string;\n readonly emptySegmentDetail?: string;\n}\n\nexport type ScopedRouteParseResult =\n | { readonly ok: true; readonly workspaceSegment?: string; readonly sessionSegment?: string }\n | { readonly ok: false; readonly problem: ProblemDetails };\n\n/**\n * {§http-admission} Parses `/<mount>[/<workspace>[/<session>]]` pathnames with URI-component decoding\n * and RFC 9457 Problem refusals on out-of-scope routes (`404`) or malformed percent-encoding (`400`).\n */\nexport const parseScopedRoute = (\n pathname: string,\n options: ScopedRouteOptions,\n): ScopedRouteParseResult => {\n const mount = options.mount.endsWith(\"/\") && options.mount.length > 1\n ? options.mount.slice(0, -1)\n : options.mount;\n const problem = (slug: string, status: number, detail: string, extra: Readonly<Record<string, unknown>> = {}): ProblemDetails =>\n Problems.create(options.domain, slug, status, detail, {\n ...(options.codePrefix === undefined ? {} : { code: `${options.codePrefix}/${slug}` }),\n path: pathname,\n stage: \"routing\",\n retryable: false,\n ...extra,\n });\n\n if (pathname === mount || pathname === `${mount}/`) {\n return { ok: true };\n }\n const prefix = `${mount}/`;\n if (!pathname.startsWith(prefix)) {\n return {\n ok: false,\n problem: problem(\"route-not-found\", 404, options.notFoundDetail ?? \"The requested HTTP route does not exist.\"),\n };\n }\n const trimmed = pathname.endsWith(\"/\") ? pathname.slice(prefix.length, -1) : pathname.slice(prefix.length);\n const rawParts = trimmed.split(\"/\");\n if (rawParts.length > 2 || rawParts.some((part) => part.length === 0)) {\n return {\n ok: false,\n problem: problem(\"route-not-found\", 404, options.notFoundDetail ?? \"The requested HTTP route does not exist.\", {\n recovery: `Use \\`${mount}\\`, \\`${mount}/<workspace>\\`, or \\`${mount}/<workspace>/<session>\\`.`,\n }),\n };\n }\n try {\n const decoded = rawParts.map((part) => decodeURIComponent(part));\n if (options.emptySegmentDetail !== undefined && decoded.some((part) => part.trim().length === 0)) {\n return {\n ok: false,\n problem: problem(\"request-target-invalid\", 400, options.emptySegmentDetail),\n };\n }\n return {\n ok: true,\n workspaceSegment: decoded[0],\n sessionSegment: decoded[1],\n };\n } catch {\n return {\n ok: false,\n problem: problem(\n \"request-target-invalid\",\n 400,\n options.malformedEncodingDetail ?? `The ${mount} route contains malformed percent-encoding.`,\n ),\n };\n }\n};\n\nexport interface BrowserOriginOptions {\n readonly allowOrigin: string;\n readonly listener: { readonly host: string; readonly port: number };\n readonly domain?: string;\n readonly codePrefix?: string;\n}\n\nexport type BrowserOriginAdmission =\n | { readonly ok: true }\n | { readonly ok: false; readonly problem: ProblemDetails };\n\n/**\n * {§http-host} {§http-admission} Enforces browser same-origin CSRF / Cross-Site WebSocket Hijacking protection\n * (`Sec-Fetch-Site` and `Origin` matching the target `Host`) when `allowOrigin` is empty, and\n * rejects browser DNS-rebinding `Host` headers on direct unproxied loopback listeners. Non-browser\n * clients (carrying neither `Origin` nor `Sec-Fetch-*`) pass through untouched.\n */\nexport const admitBrowserOrigin = (\n req: RequestHeaders,\n options: BrowserOriginOptions,\n): BrowserOriginAdmission => {\n const domain = options.domain ?? \"daemon:http\";\n const codePrefix = options.codePrefix;\n const reject = (slug: string, detail: string): BrowserOriginAdmission => ({\n ok: false,\n problem: Problems.create(domain, slug, 403, detail, {\n ...(codePrefix === undefined ? {} : { code: `${codePrefix}/${slug}` }),\n stage: \"authorization\",\n retryable: false,\n }),\n });\n\n const allowOrigin = options.allowOrigin.trim();\n const rawOrigin = firstHeader(req.headers.origin)?.trim();\n const rawFetchSite = firstHeader(req.headers[\"sec-fetch-site\"])?.trim().toLowerCase();\n const rawFetchMode = firstHeader(req.headers[\"sec-fetch-mode\"])?.trim().toLowerCase();\n const isBrowserRequest = rawOrigin !== undefined || rawFetchSite !== undefined || rawFetchMode !== undefined;\n if (!isBrowserRequest) return { ok: true };\n\n if (allowOrigin === \"*\") return { ok: true };\n if (allowOrigin.length > 0) {\n if (rawOrigin !== undefined && rawOrigin !== allowOrigin) {\n return reject(\"cross-origin-forbidden\", \"The browser Origin header does not match the configured allowed origin.\");\n }\n return { ok: true };\n }\n\n const hasForwarded =\n firstHeader(req.headers[\"x-forwarded-for\"]) !== undefined ||\n firstHeader(req.headers[\"x-forwarded-proto\"]) !== undefined ||\n firstHeader(req.headers[\"x-forwarded-host\"]) !== undefined ||\n firstHeader(req.headers.forwarded) !== undefined;\n const rawHostHeader = (firstHeader(req.headers[\"x-forwarded-host\"])?.split(\",\", 1)[0]?.trim() || firstHeader(req.headers.host)?.trim()) ?? \"\";\n\n if (isLoopbackHost(options.listener.host) && !hasForwarded && rawHostHeader.length > 0) {\n try {\n const parsedHost = new URL(`http://${rawHostHeader}`);\n if (!isLoopbackHost(parsedHost.hostname)) {\n return reject(\"host-not-allowed\", \"Browser requests to a loopback listener must target a loopback Host.\");\n }\n } catch {\n return reject(\"host-not-allowed\", \"The request Host header is malformed.\");\n }\n }\n\n if (rawFetchSite !== undefined && rawFetchSite !== \"same-origin\" && rawFetchSite !== \"none\") {\n return reject(\"cross-origin-forbidden\", \"Cross-origin browser requests are not permitted.\");\n }\n\n if (rawOrigin !== undefined) {\n if (rawOrigin === \"null\" || rawHostHeader.length === 0) {\n return reject(\"cross-origin-forbidden\", \"The browser Origin header must match the target Host.\");\n }\n try {\n const originUrl = new URL(rawOrigin);\n const expectedUrl = new URL(`${originUrl.protocol}//${rawHostHeader}`);\n if (originUrl.host.toLowerCase() !== expectedUrl.host.toLowerCase()) {\n return reject(\"cross-origin-forbidden\", \"The browser Origin header must match the target Host.\");\n }\n } catch {\n return reject(\"cross-origin-forbidden\", \"The browser Origin header is malformed.\");\n }\n }\n\n return { ok: true };\n};\n\nexport interface BearerAdmissionOptions {\n readonly allowQueryToken?: boolean;\n readonly domain?: string;\n readonly codePrefix?: string;\n}\n\nexport type BearerAdmission =\n | { readonly ok: true; readonly subject: string | null }\n | { readonly ok: false; readonly problem: ProblemDetails; readonly challenge: string };\n\nconst extractWsProtocolBearer = (rawProtocol: string | readonly string[] | undefined): string | null => {\n const joined = typeof rawProtocol === \"string\" ? rawProtocol : Array.isArray(rawProtocol) ? rawProtocol.join(\",\") : \"\";\n if (joined.length === 0) return null;\n for (const part of joined.split(\",\")) {\n const trimmed = part.trim();\n if (trimmed.startsWith(\"bearer.\") && trimmed.length > \"bearer.\".length) {\n return trimmed.slice(\"bearer.\".length);\n }\n }\n return null;\n};\n\n/**\n * {§credential-authority} {§http-host} {§http-admission} Verifies an HTTP/WebSocket request against the daemon's\n * `CredentialAuthority` using `Authorization: Bearer <token>` (or `Sec-WebSocket-Protocol: bearer.<token>` /\n * `?access_token=<token>` when `allowQueryToken` is set), returning the admitted principal `subject`\n * or an RFC 9457 Problem and RFC 6750 / RFC 9728 `WWW-Authenticate` challenge.\n */\nexport const admitBearerRequest = async (\n credentials: CredentialAuthority,\n req: RequestHeaders & { readonly url?: string | undefined },\n options: BearerAdmissionOptions = {},\n): Promise<BearerAdmission> => {\n const face = credentials.face();\n const resourceOrigin = face?.issuer(req);\n if (face === null || resourceOrigin === undefined) {\n return { ok: true, subject: null };\n }\n\n const domain = options.domain ?? \"daemon:http\";\n const codePrefix = options.codePrefix;\n const problem = (slug: string, status: number, detail: string, fields: Readonly<Record<string, unknown>>): ProblemDetails =>\n Problems.create(domain, slug, status, detail, {\n ...(codePrefix === undefined ? {} : { code: `${codePrefix}/${slug}` }),\n ...fields,\n });\n\n const header = firstHeader(req.headers.authorization);\n const challenge = (parameters: string): string =>\n `Bearer realm=\"plurnk\"${parameters}, resource_metadata=\"${resourceOrigin}/.well-known/oauth-protected-resource\"`;\n let token: string | null = null;\n if (header !== undefined) {\n const match = /^Bearer(?:\\s+(.*))?$/iu.exec(header);\n if (match !== null) token = (match[1] ?? \"\").trim();\n }\n if (token === null && options.allowQueryToken === true) {\n token = extractWsProtocolBearer(req.headers[\"sec-websocket-protocol\"]);\n if (token === null) {\n const url = new URL(req.url ?? \"/\", \"http://listener\");\n const queryToken = url.searchParams.get(\"access_token\");\n if (queryToken !== null) token = queryToken.trim();\n }\n }\n if (token === null) {\n return {\n ok: false,\n challenge: challenge(\"\"),\n problem: problem(\"bearer-token-required\", 401, \"The request did not provide a bearer token.\", {\n stage: \"authorization\",\n recovery: \"Present a valid OIDC bearer token as `Authorization: Bearer <token>`.\",\n retryable: false,\n }),\n };\n }\n const claims = token.length === 0 ? null : await credentials.verify(token);\n if (claims === null) {\n return {\n ok: false,\n challenge: challenge(\n ', error=\"invalid_token\", error_description=\"The bearer token is invalid, expired, or not authorized for this resource.\"',\n ),\n problem: problem(\"bearer-token-invalid\", 401, \"The bearer token is invalid, expired, or not authorized for this resource.\", {\n stage: \"authorization\",\n recovery: \"Obtain a valid access token from the authorization server advertised in `/.well-known/oauth-protected-resource`.\",\n retryable: false,\n }),\n };\n }\n return { ok: true, subject: claims.subject };\n};\n"]}
@@ -0,0 +1,35 @@
1
+ import { type IncomingMessage, type ServerResponse } from "node:http";
2
+ import type { Duplex } from "node:stream";
3
+ import type { ProblemDetails } from "./types.generated.ts";
4
+ /**
5
+ * {§http-admission} Writes an RFC 9457 `application/problem+json` HTTP response when headers
6
+ * have not yet been sent.
7
+ */
8
+ export declare const writeHttpProblem: (res: ServerResponse, problem: ProblemDetails, extraHeaders?: Readonly<Record<string, string>>) => void;
9
+ /**
10
+ * {§http-admission} Writes an HTTP/1.1 `application/problem+json` refusal onto a raw upgrade socket
11
+ * and closes the connection.
12
+ */
13
+ export declare const writeUpgradeProblem: (socket: Duplex, problem: ProblemDetails, extraHeaders?: Readonly<Record<string, string>>) => void;
14
+ export interface SseKeepAliveOptions {
15
+ readonly heartbeatMs: number;
16
+ readonly requireEventStreamHeader?: boolean;
17
+ readonly onClose?: () => void;
18
+ }
19
+ /**
20
+ * {§http-admission} Disables the Node HTTP socket idle timeout on an SSE stream, schedules an
21
+ * `.unref()`ed `: heartbeat\n\n` interval when `heartbeatMs > 0`, and returns an idempotent `close()`
22
+ * callback wired to `req`/`res` close and error events.
23
+ */
24
+ export declare const attachSseKeepAlive: (req: IncomingMessage, res: ServerResponse, options: SseKeepAliveOptions) => (() => void);
25
+ /**
26
+ * {§module-contract} {§http-admission} Tracks admitted asynchronous HTTP/upgrade route promises so
27
+ * `module.close()` awaits every in-flight task before returning.
28
+ */
29
+ export declare class InFlightTracker {
30
+ #private;
31
+ get size(): number;
32
+ track<T>(work: Promise<T>): Promise<T>;
33
+ drain(): Promise<void>;
34
+ }
35
+ //# sourceMappingURL=HttpPort.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"HttpPort.d.ts","sourceRoot":"","sources":["../../src/HttpPort.ts"],"names":[],"mappings":"AAEA,OAAO,EAAgB,KAAK,eAAe,EAAE,KAAK,cAAc,EAAE,MAAM,WAAW,CAAC;AACpF,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAE3D;;;GAGG;AACH,eAAO,MAAM,gBAAgB,QACpB,cAAc,WACV,cAAc,iBACT,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,KAC/C,IAUF,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,mBAAmB,WACpB,MAAM,WACL,cAAc,iBACT,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,KAC/C,IAeF,CAAC;AAEF,MAAM,WAAW,mBAAmB;IAChC,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,wBAAwB,CAAC,EAAE,OAAO,CAAC;IAC5C,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;CACjC;AAED;;;;GAIG;AACH,eAAO,MAAM,kBAAkB,QACtB,eAAe,OACf,cAAc,WACV,mBAAmB,KAC7B,CAAC,MAAM,IAAI,CAgCb,CAAC;AAEF;;;GAGG;AACH,qBAAa,eAAe;;IAGxB,IAAI,IAAI,IAAI,MAAM,CAEjB;IAED,KAAK,CAAC,CAAC,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAOrC;IAEK,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAI3B;CACJ"}
@@ -0,0 +1,106 @@
1
+ // {§http-host} {§http-admission} Node-bound HTTP Problem, WebSocket upgrade, SSE keepalive,
2
+ // and in-flight work settlement helpers exported from `@plurnk/plurnk-contracts/port`.
3
+ import { STATUS_CODES } from "node:http";
4
+ /**
5
+ * {§http-admission} Writes an RFC 9457 `application/problem+json` HTTP response when headers
6
+ * have not yet been sent.
7
+ */
8
+ export const writeHttpProblem = (res, problem, extraHeaders = {}) => {
9
+ if (res.headersSent || res.writableEnded || res.destroyed)
10
+ return;
11
+ const body = JSON.stringify(problem);
12
+ res.writeHead(problem.status, {
13
+ "content-type": "application/problem+json",
14
+ "cache-control": "no-store",
15
+ "content-length": String(Buffer.byteLength(body)),
16
+ ...extraHeaders,
17
+ });
18
+ res.end(body);
19
+ };
20
+ /**
21
+ * {§http-admission} Writes an HTTP/1.1 `application/problem+json` refusal onto a raw upgrade socket
22
+ * and closes the connection.
23
+ */
24
+ export const writeUpgradeProblem = (socket, problem, extraHeaders = {}) => {
25
+ if (socket.writableEnded || socket.destroyed)
26
+ return;
27
+ const body = JSON.stringify(problem);
28
+ const statusText = STATUS_CODES[problem.status] ?? "Error";
29
+ const lines = [
30
+ `HTTP/1.1 ${problem.status} ${statusText}`,
31
+ "Content-Type: application/problem+json",
32
+ "Cache-Control: no-store",
33
+ "Connection: close",
34
+ `Content-Length: ${Buffer.byteLength(body)}`,
35
+ ...Object.entries(extraHeaders).map(([key, value]) => `${key}: ${value}`),
36
+ "",
37
+ body,
38
+ ];
39
+ socket.end(lines.join("\r\n"));
40
+ };
41
+ /**
42
+ * {§http-admission} Disables the Node HTTP socket idle timeout on an SSE stream, schedules an
43
+ * `.unref()`ed `: heartbeat\n\n` interval when `heartbeatMs > 0`, and returns an idempotent `close()`
44
+ * callback wired to `req`/`res` close and error events.
45
+ */
46
+ export const attachSseKeepAlive = (req, res, options) => {
47
+ req.socket?.setTimeout?.(0);
48
+ let timer = null;
49
+ if (options.heartbeatMs > 0) {
50
+ timer = setInterval(() => {
51
+ if (res.writableEnded || res.destroyed)
52
+ return;
53
+ if (options.requireEventStreamHeader === true) {
54
+ if (!res.headersSent)
55
+ return;
56
+ const ct = String(res.getHeader("content-type") ?? "").toLowerCase();
57
+ if (!ct.includes("text/event-stream"))
58
+ return;
59
+ }
60
+ res.write(": heartbeat\n\n");
61
+ }, options.heartbeatMs);
62
+ timer.unref?.();
63
+ }
64
+ let closed = false;
65
+ const cleanup = () => {
66
+ if (closed)
67
+ return;
68
+ closed = true;
69
+ if (timer !== null) {
70
+ clearInterval(timer);
71
+ timer = null;
72
+ }
73
+ req.off("close", cleanup);
74
+ res.off("close", cleanup);
75
+ res.off("error", cleanup);
76
+ options.onClose?.();
77
+ };
78
+ req.on("close", cleanup);
79
+ res.on("close", cleanup);
80
+ res.on("error", cleanup);
81
+ return cleanup;
82
+ };
83
+ /**
84
+ * {§module-contract} {§http-admission} Tracks admitted asynchronous HTTP/upgrade route promises so
85
+ * `module.close()` awaits every in-flight task before returning.
86
+ */
87
+ export class InFlightTracker {
88
+ #active = new Set();
89
+ get size() {
90
+ return this.#active.size;
91
+ }
92
+ track(work) {
93
+ this.#active.add(work);
94
+ const remove = () => {
95
+ this.#active.delete(work);
96
+ };
97
+ void work.then(remove, remove);
98
+ return work;
99
+ }
100
+ async drain() {
101
+ while (this.#active.size > 0) {
102
+ await Promise.allSettled([...this.#active]);
103
+ }
104
+ }
105
+ }
106
+ //# sourceMappingURL=HttpPort.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"HttpPort.js","sourceRoot":"","sources":["../../src/HttpPort.ts"],"names":[],"mappings":"AAAA,4FAA4F;AAC5F,uFAAuF;AACvF,OAAO,EAAE,YAAY,EAA6C,MAAM,WAAW,CAAC;AAIpF;;;GAGG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAC5B,GAAmB,EACnB,OAAuB,EACvB,YAAY,GAAqC,EAAE,EAC/C,EAAE;IACN,IAAI,GAAG,CAAC,WAAW,IAAI,GAAG,CAAC,aAAa,IAAI,GAAG,CAAC,SAAS;QAAE,OAAO;IAClE,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;IACrC,GAAG,CAAC,SAAS,CAAC,OAAO,CAAC,MAAM,EAAE;QAC1B,cAAc,EAAE,0BAA0B;QAC1C,eAAe,EAAE,UAAU;QAC3B,gBAAgB,EAAE,MAAM,CAAC,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;QACjD,GAAG,YAAY;KAClB,CAAC,CAAC;IACH,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;AAClB,CAAC,CAAC;AAEF;;;GAGG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAC/B,MAAc,EACd,OAAuB,EACvB,YAAY,GAAqC,EAAE,EAC/C,EAAE;IACN,IAAI,MAAM,CAAC,aAAa,IAAI,MAAM,CAAC,SAAS;QAA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AO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QAC9B,CAAC,CAAC;QACF,KAAK,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QAC/B,OAAO,IAAI,CAAC;IAChB,CAAC;IAED,KAAK,CAAC,KAAK;QACP,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,GAAG,CAAC,EAAE,CAAC;YAC3B,MAAM,OAAO,CAAC,UAAU,CAAC,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC;QAChD,CAAC;IACL,CAAC;CACJ","sourcesContent":["// {§http-host} {§http-admission} Node-bound HTTP Problem, WebSocket upgrade, SSE keepalive,\n// and in-flight work settlement helpers exported from `@plurnk/plurnk-contracts/port`.\nimport { STATUS_CODES, type IncomingMessage, type ServerResponse } from \"node:http\";\nimport type { Duplex } from \"node:stream\";\nimport type { ProblemDetails } from \"./types.generated.ts\";\n\n/**\n * {§http-admission} Writes an RFC 9457 `application/problem+json` HTTP response when headers\n * have not yet been sent.\n */\nexport const writeHttpProblem = (\n res: ServerResponse,\n problem: ProblemDetails,\n extraHeaders: Readonly<Record<string, string>> = {},\n): void => {\n if (res.headersSent || res.writableEnded || res.destroyed) return;\n const body = JSON.stringify(problem);\n res.writeHead(problem.status, {\n \"content-type\": \"application/problem+json\",\n \"cache-control\": \"no-store\",\n \"content-length\": String(Buffer.byteLength(body)),\n ...extraHeaders,\n });\n res.end(body);\n};\n\n/**\n * {§http-admission} Writes an HTTP/1.1 `application/problem+json` refusal onto a raw upgrade socket\n * and closes the connection.\n */\nexport const writeUpgradeProblem = (\n socket: Duplex,\n problem: ProblemDetails,\n extraHeaders: Readonly<Record<string, string>> = {},\n): void => {\n if (socket.writableEnded || socket.destroyed) return;\n const body = JSON.stringify(problem);\n const statusText = STATUS_CODES[problem.status] ?? \"Error\";\n const lines = [\n `HTTP/1.1 ${problem.status} ${statusText}`,\n \"Content-Type: application/problem+json\",\n \"Cache-Control: no-store\",\n \"Connection: close\",\n `Content-Length: ${Buffer.byteLength(body)}`,\n ...Object.entries(extraHeaders).map(([key, value]) => `${key}: ${value}`),\n \"\",\n body,\n ];\n socket.end(lines.join(\"\\r\\n\"));\n};\n\nexport interface SseKeepAliveOptions {\n readonly heartbeatMs: number;\n readonly requireEventStreamHeader?: boolean;\n readonly onClose?: () => void;\n}\n\n/**\n * {§http-admission} Disables the Node HTTP socket idle timeout on an SSE stream, schedules an\n * `.unref()`ed `: heartbeat\\n\\n` interval when `heartbeatMs > 0`, and returns an idempotent `close()`\n * callback wired to `req`/`res` close and error events.\n */\nexport const attachSseKeepAlive = (\n req: IncomingMessage,\n res: ServerResponse,\n options: SseKeepAliveOptions,\n): (() => void) => {\n req.socket?.setTimeout?.(0);\n let timer: ReturnType<typeof setInterval> | null = null;\n if (options.heartbeatMs > 0) {\n timer = setInterval(() => {\n if (res.writableEnded || res.destroyed) return;\n if (options.requireEventStreamHeader === true) {\n if (!res.headersSent) return;\n const ct = String(res.getHeader(\"content-type\") ?? \"\").toLowerCase();\n if (!ct.includes(\"text/event-stream\")) return;\n }\n res.write(\": heartbeat\\n\\n\");\n }, options.heartbeatMs);\n timer.unref?.();\n }\n let closed = false;\n const cleanup = (): void => {\n if (closed) return;\n closed = true;\n if (timer !== null) {\n clearInterval(timer);\n timer = null;\n }\n req.off(\"close\", cleanup);\n res.off(\"close\", cleanup);\n res.off(\"error\", cleanup);\n options.onClose?.();\n };\n req.on(\"close\", cleanup);\n res.on(\"close\", cleanup);\n res.on(\"error\", cleanup);\n return cleanup;\n};\n\n/**\n * {§module-contract} {§http-admission} Tracks admitted asynchronous HTTP/upgrade route promises so\n * `module.close()` awaits every in-flight task before returning.\n */\nexport class InFlightTracker {\n readonly #active = new Set<Promise<unknown>>();\n\n get size(): number {\n return this.#active.size;\n }\n\n track<T>(work: Promise<T>): Promise<T> {\n this.#active.add(work);\n const remove = (): void => {\n this.#active.delete(work);\n };\n void work.then(remove, remove);\n return work;\n }\n\n async drain(): Promise<void> {\n while (this.#active.size > 0) {\n await Promise.allSettled([...this.#active]);\n }\n }\n}\n"]}