@mostra/runtime 0.13.0 → 0.14.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/bin.js +1777 -1535
- package/dist/bin.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/{instance-D5gh-sMM.js → instance-CFTw3g-c.js} +211 -22
- package/dist/instance-CFTw3g-c.js.map +1 -0
- package/dist/reference/self-hosting.md +1 -0
- package/dist/skill/SKILL.md +2 -2
- package/dist/skill/assets/examples/dashboard/styles.css +27 -9
- package/dist/skill/assets/examples/decision/styles.css +27 -9
- package/dist/skill/assets/examples/inbox/styles.css +27 -9
- package/dist/skill/assets/studio.css +27 -9
- package/dist/skill/references/mcp.md +2 -2
- package/package.json +7 -6
- package/src/gateway/http.ts +15 -19
- package/src/gateway/index.ts +67 -1
- package/src/gateway/listener.ts +10 -5
- package/src/gateway/routes.ts +6 -1
- package/src/gateway/theme.ts +238 -0
- package/src/server/api.ts +78 -86
- package/src/server/authorize.ts +47 -54
- package/src/server/config.ts +45 -0
- package/src/server/hosted.ts +5 -0
- package/src/server/index.ts +82 -2
- package/src/server/pages.ts +242 -0
- package/dist/instance-D5gh-sMM.js.map +0 -1
package/dist/bin.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { A as
|
|
2
|
+
import { $ as readProcess, A as themePageCsp, B as appendEvent, C as jsonResponse, D as defaultPages, E as THEME_BASE, F as finishRun, G as ProtocolServer, H as MAX_FRAME_BYTES, I as markRunning, J as openLedger, K as handler, L as markUnknown, M as createInteraction, N as createEphemeralBus, O as refusalDocument, P as appendRunOutput, Q as readServerFunctions, R as markWaiting, S as isRefusal, T as MADE_WITH_HREF, U as serveWebSocket, V as BINDING_SUBPROTOCOL, W as attachInProcess, X as noFaults, Y as faultsFrom, Z as readFieldCoverage, _ as resetOnClose, a as uninstallService, b as BASE_HEADERS$1, c as resolveHomePath, d as versionIdFor, et as coverageMatcher, f as createLive, g as shellAssetResponse, h as locateShell, i as serviceStatus, j as openRegistry, k as serverPages, l as canonicalRef, m as createGateway, n as startInstance, o as checkPlatform, p as liveMethods, q as holdLock, r as installService, s as platformName, t as runtimeVersion, tt as openFileLog, u as listingDigest, v as Capabilities, w as readJsonObject, x as documentHeaders, y as capabilityKey, z as runState } from "./instance-CFTw3g-c.js";
|
|
3
3
|
import { c as removeTree, s as realPath } from "./files-DGeWuE4I.js";
|
|
4
4
|
import { d as runtimeRoot, i as ownedDirectory } from "./directories-BLJjeSPD.js";
|
|
5
5
|
import { createWriteStream, existsSync, linkSync, mkdirSync, readFileSync, renameSync, statSync, statfsSync, writeFileSync } from "node:fs";
|
|
@@ -11,6 +11,7 @@ import { isIP, isIPv4, isIPv6 } from "node:net";
|
|
|
11
11
|
import { execFileSync } from "node:child_process";
|
|
12
12
|
import { copyFile, readFile, rm, stat } from "node:fs/promises";
|
|
13
13
|
import * as z from "zod";
|
|
14
|
+
import { actions, alert, appearanceCookie, button, field, fine, html, linkButton, readAppearance, safeHref } from "@mostra/themes";
|
|
14
15
|
import { createServer as createServer$1, request } from "node:http";
|
|
15
16
|
import { getRequestListener } from "@hono/node-server";
|
|
16
17
|
import { createAuthorizedEndpoint, fileDocs } from "@mostra/mcp";
|
|
@@ -100,848 +101,159 @@ function networkFilesystem(dir) {
|
|
|
100
101
|
}
|
|
101
102
|
}
|
|
102
103
|
//#endregion
|
|
103
|
-
//#region src/server/
|
|
104
|
-
/**
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
const
|
|
116
|
-
|
|
117
|
-
const
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
}
|
|
124
|
-
function send(response, status, body, headers = {}) {
|
|
125
|
-
const text = JSON.stringify(body);
|
|
126
|
-
response.writeHead(status, {
|
|
127
|
-
...BASE_HEADERS,
|
|
128
|
-
"content-type": "application/json; charset=utf-8",
|
|
129
|
-
"content-length": String(Buffer.byteLength(text)),
|
|
130
|
-
...headers
|
|
131
|
-
});
|
|
132
|
-
response.end(text);
|
|
133
|
-
}
|
|
134
|
-
function page(response, status, html) {
|
|
135
|
-
response.writeHead(status, {
|
|
136
|
-
...BASE_HEADERS,
|
|
137
|
-
"content-type": "text/html; charset=utf-8",
|
|
138
|
-
"content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'",
|
|
139
|
-
"x-frame-options": "DENY",
|
|
140
|
-
"referrer-policy": "same-origin"
|
|
141
|
-
});
|
|
142
|
-
response.end(html);
|
|
143
|
-
}
|
|
144
|
-
async function readBody(request, limit) {
|
|
145
|
-
const chunks = [];
|
|
146
|
-
let size = 0;
|
|
147
|
-
for await (const chunk of request) {
|
|
148
|
-
size += chunk.length;
|
|
149
|
-
if (size > limit) return void 0;
|
|
150
|
-
chunks.push(chunk);
|
|
104
|
+
//#region src/server/clients.ts
|
|
105
|
+
/** An address as a number (IPv4 in 32 bits, IPv6 in 128), or `undefined` when it isn't one. */
|
|
106
|
+
function addressBits(address) {
|
|
107
|
+
let text = address.trim();
|
|
108
|
+
if (text.startsWith("[") && text.endsWith("]")) text = text.slice(1, -1);
|
|
109
|
+
const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(text);
|
|
110
|
+
if (mapped) text = mapped[1];
|
|
111
|
+
if (isIPv4(text)) return {
|
|
112
|
+
v6: false,
|
|
113
|
+
bits: text.split(".").map(Number).reduce((sum, part) => sum << 8n | BigInt(part), 0n)
|
|
114
|
+
};
|
|
115
|
+
if (!isIPv6(text)) return void 0;
|
|
116
|
+
const zone = text.indexOf("%");
|
|
117
|
+
if (zone !== -1) text = text.slice(0, zone);
|
|
118
|
+
const last = text.slice(text.lastIndexOf(":") + 1);
|
|
119
|
+
if (last.includes(".")) {
|
|
120
|
+
if (!isIPv4(last)) return void 0;
|
|
121
|
+
const parts = last.split(".").map(Number);
|
|
122
|
+
const high = (parts[0] << 8 | parts[1]).toString(16);
|
|
123
|
+
const low = (parts[2] << 8 | parts[3]).toString(16);
|
|
124
|
+
text = `${text.slice(0, -last.length)}${high}:${low}`;
|
|
151
125
|
}
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
126
|
+
const [head, tail] = text.split("::");
|
|
127
|
+
const left = head === "" ? [] : head.split(":");
|
|
128
|
+
const right = tail === void 0 ? [] : tail === "" ? [] : tail.split(":");
|
|
129
|
+
const groups = tail === void 0 ? left : [
|
|
130
|
+
...left,
|
|
131
|
+
...new Array(8 - left.length - right.length).fill("0"),
|
|
132
|
+
...right
|
|
133
|
+
];
|
|
134
|
+
if (groups.length !== 8) return void 0;
|
|
135
|
+
return {
|
|
136
|
+
v6: true,
|
|
137
|
+
bits: groups.reduce((sum, group) => sum << 16n | BigInt(Number.parseInt(group, 16)), 0n)
|
|
138
|
+
};
|
|
156
139
|
}
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
const
|
|
160
|
-
return
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
140
|
+
function parseRange(text) {
|
|
141
|
+
const [address, prefixText] = text.split("/");
|
|
142
|
+
const found = addressBits(address);
|
|
143
|
+
if (!found) return void 0;
|
|
144
|
+
const width = found.v6 ? 128 : 32;
|
|
145
|
+
const prefix = prefixText === void 0 ? width : Number(prefixText);
|
|
146
|
+
if (!Number.isInteger(prefix) || prefix < 0 || prefix > width) return void 0;
|
|
147
|
+
return {
|
|
148
|
+
v6: found.v6,
|
|
149
|
+
bits: found.bits,
|
|
150
|
+
prefix
|
|
151
|
+
};
|
|
164
152
|
}
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
<style>body{font:16px/1.5 system-ui,sans-serif;max-width:34rem;margin:3rem auto;padding:0 1rem}
|
|
170
|
-
input{font:inherit;padding:.3rem}button{font:inherit;padding:.4rem .9rem;margin-right:.5rem}</style></head>
|
|
171
|
-
<body><h1>Link a machine to Mostra</h1>${options.done ? `<p>${escapeHtml$1(options.message ?? "Done.")}</p><p>You can close this page.</p>` : `${options.message ? `<p role="alert">${escapeHtml$1(options.message)}</p>` : ""}
|
|
172
|
-
<p><strong>Approving links a machine to your account.</strong> That machine's Mostra can then host
|
|
173
|
-
pages under your account and receives their answers. Continue only if you started this sign-in
|
|
174
|
-
yourself, on that machine.</p>
|
|
175
|
-
${options.provider ? `<form method="post" action="/device">
|
|
176
|
-
<label>Code <input name="user_code" value="${escapeHtml$1(options.code)}" autocomplete="off" required></label>
|
|
177
|
-
<p>${escapeHtml$1(options.provider.label)}: this server signs people in with a development provider,
|
|
178
|
-
which trusts the name you type. Use it only on a server you run for yourself or for tests.</p>
|
|
179
|
-
<label>Your name <input name="name" required maxlength="64"></label>
|
|
180
|
-
<input type="hidden" name="provider" value="${escapeHtml$1(options.provider.id)}">
|
|
181
|
-
<p><button name="decision" value="approve">Approve this machine</button>
|
|
182
|
-
<button name="decision" value="deny">Refuse</button></p>
|
|
183
|
-
</form>` : "<p>This server has no identity provider configured, so nobody can sign in yet.</p>"}`}</body></html>`;
|
|
153
|
+
function inRange(range, address) {
|
|
154
|
+
if (range.v6 !== address.v6) return false;
|
|
155
|
+
const shift = (range.v6 ? 128n : 32n) - BigInt(range.prefix);
|
|
156
|
+
return range.bits >> shift === address.bits >> shift;
|
|
184
157
|
}
|
|
185
|
-
/**
|
|
186
|
-
function
|
|
187
|
-
return
|
|
188
|
-
<meta name="viewport" content="width=device-width, initial-scale=1"><title>Link a machine to Mostra</title>
|
|
189
|
-
<style>body{font:16px/1.5 system-ui,sans-serif;max-width:34rem;margin:3rem auto;padding:0 1rem}
|
|
190
|
-
input{font:inherit;padding:.3rem}button{font:inherit;padding:.4rem .9rem;margin-right:.5rem}</style></head>
|
|
191
|
-
<body><h1>Link a machine to Mostra</h1>
|
|
192
|
-
<p><strong>Approving links a machine to your account, ${escapeHtml$1(options.name)}.</strong> That machine's
|
|
193
|
-
Mostra can then host pages under your account and receives their answers. Continue only if you started
|
|
194
|
-
this sign-in yourself, on that machine.</p>
|
|
195
|
-
<form method="post" action="/device"><input type="hidden" name="csrf" value="${escapeHtml$1(options.csrf)}">
|
|
196
|
-
<label>Code <input name="user_code" value="${escapeHtml$1(options.code)}" autocomplete="off" required></label>
|
|
197
|
-
<p><button name="session_decision" value="approve">Approve this machine</button>
|
|
198
|
-
<button name="session_decision" value="deny">Refuse</button></p></form></body></html>`;
|
|
158
|
+
/** Whether every entry of `trustedProxies` is an address or a CIDR block. */
|
|
159
|
+
function validProxies(entries) {
|
|
160
|
+
return entries.find((entry) => parseRange(entry) === void 0);
|
|
199
161
|
}
|
|
200
|
-
/**
|
|
201
|
-
function
|
|
202
|
-
const
|
|
203
|
-
const
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
maxPayload: MAX_FRAME_BYTES,
|
|
207
|
-
perMessageDeflate: false,
|
|
208
|
-
handleProtocols: (protocols) => protocols.has("mostra.host") ? BINDING_SUBPROTOCOL : false
|
|
209
|
-
});
|
|
210
|
-
const bindings = /* @__PURE__ */ new Set();
|
|
211
|
-
const bindingHomes = /* @__PURE__ */ new Map();
|
|
212
|
-
/**
|
|
213
|
-
* Whether the device page offers the development provider's form (D166 item 4): only while it is
|
|
214
|
-
* the one provider a sign-in may use now, none other configured and none the operator supplies.
|
|
215
|
-
* The page's GET and its POST judge by this one rule.
|
|
216
|
-
*/
|
|
217
|
-
const devFormOffered = async () => {
|
|
218
|
-
const development = developmentProvider$1(config);
|
|
219
|
-
if (development === void 0) return false;
|
|
220
|
-
const offered = await options.authorize.providers();
|
|
221
|
-
return offered.length === 1 && offered[0]?.id === development.id;
|
|
162
|
+
/** Builds the resolver; an entry that isn't an address or a block is ignored (checked at start). */
|
|
163
|
+
function clientAddresses(options) {
|
|
164
|
+
const proxies = (options.trustedProxies ?? []).map(parseRange).filter((range) => range !== void 0);
|
|
165
|
+
const trusted = (address) => {
|
|
166
|
+
const bits = addressBits(address);
|
|
167
|
+
return bits !== void 0 && proxies.some((range) => inRange(range, bits));
|
|
222
168
|
};
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
169
|
+
const ipv6Prefix = options.ipv6Prefix ?? 64;
|
|
170
|
+
const seen = /* @__PURE__ */ new WeakMap();
|
|
171
|
+
return {
|
|
172
|
+
of(incoming) {
|
|
173
|
+
if (seen.has(incoming)) return seen.get(incoming);
|
|
174
|
+
const peer = incoming.socket.remoteAddress;
|
|
175
|
+
let client = peer;
|
|
176
|
+
if (peer !== void 0 && trusted(peer)) {
|
|
177
|
+
const header = incoming.headers["x-forwarded-for"];
|
|
178
|
+
const entries = (Array.isArray(header) ? header.join(",") : header ?? "").split(",").map((entry) => entry.trim()).filter((entry) => entry !== "");
|
|
179
|
+
for (let index = entries.length - 1; index >= 0; index--) {
|
|
180
|
+
const entry = entries[index];
|
|
181
|
+
if (addressBits(entry) === void 0) break;
|
|
182
|
+
client = entry;
|
|
183
|
+
if (!trusted(entry)) break;
|
|
184
|
+
}
|
|
239
185
|
}
|
|
186
|
+
seen.set(incoming, client);
|
|
187
|
+
return client;
|
|
188
|
+
},
|
|
189
|
+
keyOf(address) {
|
|
190
|
+
if (address === void 0) return "unknown";
|
|
191
|
+
const bits = addressBits(address);
|
|
192
|
+
if (!bits) return `other:${address}`;
|
|
193
|
+
if (!bits.v6) return `v4:${bits.bits.toString(16)}`;
|
|
194
|
+
const shift = 128n - BigInt(ipv6Prefix);
|
|
195
|
+
return `v6:${(bits.bits >> shift).toString(16)}/${ipv6Prefix}`;
|
|
240
196
|
}
|
|
241
|
-
return auth.accountStatus(accountId);
|
|
242
197
|
};
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* A token-bucket rate limiter over keys, in memory, bounded in the keys it keeps: each key holds up
|
|
201
|
+
* to `count` tokens and earns them back at `count` per `perMs`, so a burst of `count` passes and
|
|
202
|
+
* the sustained rate is exactly the rate.
|
|
203
|
+
*/
|
|
204
|
+
var RateLimiter = class {
|
|
205
|
+
#buckets = /* @__PURE__ */ new Map();
|
|
206
|
+
#now;
|
|
207
|
+
#maxKeys;
|
|
208
|
+
constructor(options = {}) {
|
|
209
|
+
this.#now = options.now ?? (() => Date.now());
|
|
210
|
+
this.#maxKeys = options.maxKeys ?? 1e5;
|
|
211
|
+
}
|
|
212
|
+
/** A key's bucket, refilled to now and marked most recently used, so the bound drops the least. */
|
|
213
|
+
#bucket(key, rate, now) {
|
|
214
|
+
const perToken = rate.perMs / rate.count;
|
|
215
|
+
let bucket = this.#buckets.get(key);
|
|
216
|
+
if (bucket) {
|
|
217
|
+
bucket.tokens = Math.min(rate.count, bucket.tokens + (now - bucket.at) / perToken);
|
|
218
|
+
bucket.at = now;
|
|
219
|
+
this.#buckets.delete(key);
|
|
220
|
+
} else {
|
|
221
|
+
if (this.#buckets.size >= this.#maxKeys) this.#buckets.delete(this.#buckets.keys().next().value);
|
|
222
|
+
bucket = {
|
|
223
|
+
tokens: rate.count,
|
|
224
|
+
at: now
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
this.#buckets.set(key, bucket);
|
|
228
|
+
return bucket;
|
|
229
|
+
}
|
|
230
|
+
/** How long until every bucket holds a token: 0 when they all do now. */
|
|
231
|
+
#wait(wanted, now) {
|
|
232
|
+
let waitMs = 0;
|
|
233
|
+
const buckets = wanted.map(({ key, rate }) => {
|
|
234
|
+
const bucket = this.#bucket(key, rate, now);
|
|
235
|
+
if (bucket.tokens < 1) waitMs = Math.max(waitMs, (1 - bucket.tokens) * (rate.perMs / rate.count));
|
|
236
|
+
return bucket;
|
|
237
|
+
});
|
|
238
|
+
return {
|
|
239
|
+
waitMs,
|
|
240
|
+
buckets
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
243
|
/**
|
|
244
|
-
*
|
|
245
|
-
*
|
|
246
|
-
* (Fable review of WP-30, 1).
|
|
244
|
+
* Takes one token under `key` when there is one. Without one, nothing is taken and the answer
|
|
245
|
+
* says when to try again, in whole seconds (`Retry-After`).
|
|
247
246
|
*/
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
247
|
+
take(key, rate) {
|
|
248
|
+
return this.takeAll([{
|
|
249
|
+
key,
|
|
250
|
+
rate
|
|
251
|
+
}]);
|
|
252
|
+
}
|
|
251
253
|
/**
|
|
252
|
-
*
|
|
253
|
-
*
|
|
254
|
-
*
|
|
255
|
-
*/
|
|
256
|
-
const bearer = async (request, resource) => {
|
|
257
|
-
const header = request.headers.authorization ?? "";
|
|
258
|
-
const match = /^bearer\s+(\S+)$/i.exec(header);
|
|
259
|
-
if (!match) return void 0;
|
|
260
|
-
const token = match[1];
|
|
261
|
-
const audience = `${apiOrigin}/${resource === "files" ? "host" : resource}`;
|
|
262
|
-
const issued = auth.authenticate(token);
|
|
263
|
-
let who;
|
|
264
|
-
if (issued) {
|
|
265
|
-
if (issued.resource !== audience) return void 0;
|
|
266
|
-
who = issued;
|
|
267
|
-
} else {
|
|
268
|
-
if (!options.operator?.has.authenticate) return void 0;
|
|
269
|
-
const credential = await options.operator.authenticate(token, resource);
|
|
270
|
-
if (!credential?.scope.includes("mostra")) return void 0;
|
|
271
|
-
who = auth.credentialSession({
|
|
272
|
-
account: credential.account,
|
|
273
|
-
subject: credential.subject ?? "default",
|
|
274
|
-
resource: audience,
|
|
275
|
-
link: resource === "host"
|
|
276
|
-
});
|
|
277
|
-
}
|
|
278
|
-
const refused = await standing(who);
|
|
279
|
-
return refused ? { refused } : who;
|
|
280
|
-
};
|
|
281
|
-
const unauthorized = (response, message) => send(response, 401, {
|
|
282
|
-
code: "MOSTRA_REMOTE_LOGIN_FAILED",
|
|
283
|
-
message
|
|
284
|
-
}, { "www-authenticate": `Bearer resource_metadata="${apiOrigin}/.well-known/oauth-protected-resource/host"` });
|
|
285
|
-
/**
|
|
286
|
-
* RFC 8414 metadata (INTERFACES §18.5): Client ID Metadata Documents with `none` among the token
|
|
287
|
-
* endpoint's methods, which Claude needs before it uses one, Dynamic Client Registration as the
|
|
288
|
-
* fallback, PKCE S256, `iss` in responses, and `offline_access` for rotating refresh tokens.
|
|
289
|
-
*/
|
|
290
|
-
const metadata = () => ({
|
|
291
|
-
issuer: apiOrigin,
|
|
292
|
-
authorization_endpoint: `${apiOrigin}/oauth/authorize`,
|
|
293
|
-
token_endpoint: `${apiOrigin}/oauth/token`,
|
|
294
|
-
registration_endpoint: `${apiOrigin}/oauth/register`,
|
|
295
|
-
device_authorization_endpoint: `${apiOrigin}/oauth/device`,
|
|
296
|
-
revocation_endpoint: `${apiOrigin}/oauth/revoke`,
|
|
297
|
-
response_types_supported: ["code"],
|
|
298
|
-
response_modes_supported: ["query"],
|
|
299
|
-
grant_types_supported: [
|
|
300
|
-
"authorization_code",
|
|
301
|
-
"refresh_token",
|
|
302
|
-
"urn:ietf:params:oauth:grant-type:device_code"
|
|
303
|
-
],
|
|
304
|
-
token_endpoint_auth_methods_supported: ["none"],
|
|
305
|
-
revocation_endpoint_auth_methods_supported: ["none"],
|
|
306
|
-
code_challenge_methods_supported: ["S256"],
|
|
307
|
-
scopes_supported: ["mostra", "offline_access"],
|
|
308
|
-
client_id_metadata_document_supported: true,
|
|
309
|
-
authorization_response_iss_parameter_supported: true
|
|
310
|
-
});
|
|
311
|
-
const sessionDevicePage = (code, signed) => deviceApproval({
|
|
312
|
-
code,
|
|
313
|
-
name: auth.accountName(signed.accountId).name ?? "your account",
|
|
314
|
-
csrf: options.authorize.csrf(signed.hash, "device")
|
|
315
|
-
});
|
|
316
|
-
const form = async (request) => {
|
|
317
|
-
if (!(request.headers["content-type"] ?? "").startsWith("application/x-www-form-urlencoded")) return void 0;
|
|
318
|
-
const body = await readBody(request, 65536);
|
|
319
|
-
return body === void 0 ? void 0 : new URLSearchParams(body.toString("utf8"));
|
|
320
|
-
};
|
|
321
|
-
const upload = async (request, response, sha) => {
|
|
322
|
-
const who = await bearer(request, "files");
|
|
323
|
-
if (!who) {
|
|
324
|
-
unauthorized(response, "Version files need the binding's access token.");
|
|
325
|
-
return;
|
|
326
|
-
}
|
|
327
|
-
if ("refused" in who) {
|
|
328
|
-
send(response, 403, who.refused);
|
|
329
|
-
return;
|
|
330
|
-
}
|
|
331
|
-
const home = await options.home(who.homeId);
|
|
332
|
-
options.touch(who.homeId);
|
|
333
|
-
const declared = home.wanted(sha);
|
|
334
|
-
if (declared === void 0) {
|
|
335
|
-
send(response, 409, {
|
|
336
|
-
code: "MOSTRA_HOME_INTEGRITY",
|
|
337
|
-
message: "No pending push of this home names that file as missing."
|
|
338
|
-
});
|
|
339
|
-
return;
|
|
340
|
-
}
|
|
341
|
-
/** Refuses the upload and closes its connection once the answer is out: the rest isn't read. */
|
|
342
|
-
const refuseUpload = (status, message) => {
|
|
343
|
-
response.once("finish", () => request.destroy());
|
|
344
|
-
send(response, status, {
|
|
345
|
-
code: "MOSTRA_HOME_INTEGRITY",
|
|
346
|
-
message
|
|
347
|
-
}, { connection: "close" });
|
|
348
|
-
};
|
|
349
|
-
const sizeMessage = "The file's bytes aren't the size its push gave them.";
|
|
350
|
-
const announced = request.headers["content-length"];
|
|
351
|
-
if (announced !== void 0 && Number(announced) !== declared) {
|
|
352
|
-
refuseUpload(declared > MAX_FILE_BYTES ? 413 : 400, sizeMessage);
|
|
353
|
-
return;
|
|
354
|
-
}
|
|
355
|
-
const target = join(options.filesDir, sha);
|
|
356
|
-
const scratch = join(options.filesDir, `.upload-${randomBytes(8).toString("hex")}`);
|
|
357
|
-
const hash = createHash("sha256");
|
|
358
|
-
let size = 0;
|
|
359
|
-
let tooLarge = false;
|
|
360
|
-
await new Promise((resolve, reject) => {
|
|
361
|
-
const out = createWriteStream(scratch, { mode: 384 });
|
|
362
|
-
const onData = (chunk) => {
|
|
363
|
-
size += chunk.length;
|
|
364
|
-
if (size > MAX_FILE_BYTES || size > declared) {
|
|
365
|
-
tooLarge = true;
|
|
366
|
-
request.off("data", onData);
|
|
367
|
-
request.pause();
|
|
368
|
-
out.end(() => resolve());
|
|
369
|
-
return;
|
|
370
|
-
}
|
|
371
|
-
hash.update(chunk);
|
|
372
|
-
out.write(chunk);
|
|
373
|
-
};
|
|
374
|
-
request.on("data", onData);
|
|
375
|
-
request.on("end", () => {
|
|
376
|
-
if (!tooLarge) out.end(() => resolve());
|
|
377
|
-
});
|
|
378
|
-
request.on("error", reject);
|
|
379
|
-
request.on("close", () => out.end(() => resolve()));
|
|
380
|
-
}).catch(() => void 0);
|
|
381
|
-
const shortOrLong = !tooLarge && size !== declared;
|
|
382
|
-
if (tooLarge || shortOrLong || hash.digest("hex") !== sha) {
|
|
383
|
-
await rm(scratch, { force: true });
|
|
384
|
-
refuseUpload(tooLarge && size > MAX_FILE_BYTES ? 413 : 400, tooLarge || shortOrLong ? sizeMessage : "The bytes don't hash to the file's name.");
|
|
385
|
-
return;
|
|
386
|
-
}
|
|
387
|
-
if (existsSync(target)) await rm(scratch, { force: true });
|
|
388
|
-
else renameSync(scratch, target);
|
|
389
|
-
home.uploaded(sha, size);
|
|
390
|
-
options.stored?.(who.homeId, size);
|
|
391
|
-
send(response, 201, {
|
|
392
|
-
sha256: sha,
|
|
393
|
-
size
|
|
394
|
-
});
|
|
395
|
-
};
|
|
396
|
-
return {
|
|
397
|
-
async request(request, response, path) {
|
|
398
|
-
const method = request.method ?? "GET";
|
|
399
|
-
if (method === "GET" && path === "/.well-known/oauth-authorization-server") {
|
|
400
|
-
send(response, 200, metadata());
|
|
401
|
-
return;
|
|
402
|
-
}
|
|
403
|
-
if (await options.authorize.handle(request, response, path)) return;
|
|
404
|
-
if (method === "GET" && path === "/.well-known/oauth-protected-resource/mcp") {
|
|
405
|
-
send(response, 200, {
|
|
406
|
-
resource: `${apiOrigin}/mcp`,
|
|
407
|
-
authorization_servers: [apiOrigin],
|
|
408
|
-
scopes_supported: ["mostra"],
|
|
409
|
-
bearer_methods_supported: ["header"],
|
|
410
|
-
resource_name: "Mostra"
|
|
411
|
-
});
|
|
412
|
-
return;
|
|
413
|
-
}
|
|
414
|
-
if (method === "POST" && path === "/link") {
|
|
415
|
-
const who = await bearer(request, "host");
|
|
416
|
-
if (who && "refused" in who) {
|
|
417
|
-
send(response, 403, who.refused);
|
|
418
|
-
return;
|
|
419
|
-
}
|
|
420
|
-
if (!who || who.linkId === void 0) {
|
|
421
|
-
unauthorized(response, "This credential links no instance on this server.");
|
|
422
|
-
return;
|
|
423
|
-
}
|
|
424
|
-
const body = await form(request);
|
|
425
|
-
const linked = auth.linkState(who.linkId, body?.get("default") === "1");
|
|
426
|
-
send(response, 200, {
|
|
427
|
-
account: {
|
|
428
|
-
id: who.accountId,
|
|
429
|
-
...who.accountName !== void 0 ? { name: who.accountName } : {}
|
|
430
|
-
},
|
|
431
|
-
instanceId: who.linkId,
|
|
432
|
-
default: linked.default
|
|
433
|
-
});
|
|
434
|
-
return;
|
|
435
|
-
}
|
|
436
|
-
if (method === "POST" && path === "/oauth/register") {
|
|
437
|
-
if (!(request.headers["content-type"] ?? "").startsWith("application/json")) {
|
|
438
|
-
send(response, 400, {
|
|
439
|
-
error: "invalid_client_metadata",
|
|
440
|
-
error_description: "Send JSON."
|
|
441
|
-
});
|
|
442
|
-
return;
|
|
443
|
-
}
|
|
444
|
-
const body = await readBody(request, 65536);
|
|
445
|
-
let metadata;
|
|
446
|
-
try {
|
|
447
|
-
metadata = JSON.parse(body?.toString("utf8") ?? "");
|
|
448
|
-
} catch {
|
|
449
|
-
send(response, 400, {
|
|
450
|
-
error: "invalid_client_metadata",
|
|
451
|
-
error_description: "Send JSON."
|
|
452
|
-
});
|
|
453
|
-
return;
|
|
454
|
-
}
|
|
455
|
-
if (options.registrations) {
|
|
456
|
-
const { addresses, rates } = options.registrations;
|
|
457
|
-
const taken = rates.take(`register:${addresses.keyOf(addresses.of(request))}`, {
|
|
458
|
-
count: REGISTRATIONS_PER_MINUTE,
|
|
459
|
-
perMs: 6e4
|
|
460
|
-
});
|
|
461
|
-
if (!taken.ok) {
|
|
462
|
-
send(response, 429, {
|
|
463
|
-
error: "slow_down",
|
|
464
|
-
error_description: "Too many registrations from this address; try again shortly."
|
|
465
|
-
}, { "retry-after": String(taken.retryAfterS) });
|
|
466
|
-
return;
|
|
467
|
-
}
|
|
468
|
-
}
|
|
469
|
-
const registered = options.clients.register(metadata);
|
|
470
|
-
if ("error" in registered && "description" in registered) {
|
|
471
|
-
send(response, 400, {
|
|
472
|
-
error: registered["error"],
|
|
473
|
-
error_description: registered["description"]
|
|
474
|
-
});
|
|
475
|
-
return;
|
|
476
|
-
}
|
|
477
|
-
send(response, 201, registered);
|
|
478
|
-
return;
|
|
479
|
-
}
|
|
480
|
-
if (method === "GET" && path === "/.well-known/oauth-protected-resource/host") {
|
|
481
|
-
send(response, 200, {
|
|
482
|
-
resource: `${apiOrigin}/host`,
|
|
483
|
-
authorization_servers: [apiOrigin],
|
|
484
|
-
scopes_supported: ["mostra"]
|
|
485
|
-
});
|
|
486
|
-
return;
|
|
487
|
-
}
|
|
488
|
-
if (method === "POST" && path === "/oauth/device") {
|
|
489
|
-
const body = await form(request);
|
|
490
|
-
if (!body) {
|
|
491
|
-
send(response, 400, {
|
|
492
|
-
error: "invalid_request",
|
|
493
|
-
error_description: "Send a form."
|
|
494
|
-
});
|
|
495
|
-
return;
|
|
496
|
-
}
|
|
497
|
-
const answer = auth.device(body);
|
|
498
|
-
if ("error" in answer && typeof answer["status"] === "number") {
|
|
499
|
-
const failed = answer;
|
|
500
|
-
send(response, failed.status, {
|
|
501
|
-
error: failed.error,
|
|
502
|
-
error_description: failed.description
|
|
503
|
-
});
|
|
504
|
-
return;
|
|
505
|
-
}
|
|
506
|
-
send(response, 200, answer);
|
|
507
|
-
return;
|
|
508
|
-
}
|
|
509
|
-
if (method === "POST" && path === "/oauth/token") {
|
|
510
|
-
const body = await form(request);
|
|
511
|
-
if (!body) {
|
|
512
|
-
send(response, 400, {
|
|
513
|
-
error: "invalid_request",
|
|
514
|
-
error_description: "Send a form."
|
|
515
|
-
});
|
|
516
|
-
return;
|
|
517
|
-
}
|
|
518
|
-
if (body.get("grant_type") === "refresh_token") {
|
|
519
|
-
const account = auth.refreshAccount(body.get("refresh_token") ?? "");
|
|
520
|
-
if (account !== void 0) await accountStanding(account);
|
|
521
|
-
}
|
|
522
|
-
const answer = auth.token(body);
|
|
523
|
-
if ("error" in answer) {
|
|
524
|
-
send(response, answer.status, {
|
|
525
|
-
error: answer.error,
|
|
526
|
-
error_description: answer.description
|
|
527
|
-
});
|
|
528
|
-
return;
|
|
529
|
-
}
|
|
530
|
-
send(response, 200, answer);
|
|
531
|
-
return;
|
|
532
|
-
}
|
|
533
|
-
if (method === "POST" && path === "/oauth/revoke") {
|
|
534
|
-
const body = await form(request);
|
|
535
|
-
if (body) auth.revoke(body);
|
|
536
|
-
send(response, 200, {});
|
|
537
|
-
return;
|
|
538
|
-
}
|
|
539
|
-
if (path === "/device") {
|
|
540
|
-
const provider = developmentProvider$1(config);
|
|
541
|
-
const signed = options.authorize.sessionAccount(request);
|
|
542
|
-
if (method === "GET") {
|
|
543
|
-
const code = new URL(request.url ?? "/", apiOrigin).searchParams.get("user_code") ?? "";
|
|
544
|
-
if (signed) {
|
|
545
|
-
page(response, 200, sessionDevicePage(code, signed));
|
|
546
|
-
return;
|
|
547
|
-
}
|
|
548
|
-
if (!await devFormOffered()) {
|
|
549
|
-
await options.authorize.signInPage(response, `/device?user_code=${encodeURIComponent(code)}`);
|
|
550
|
-
return;
|
|
551
|
-
}
|
|
552
|
-
page(response, 200, devicePage({
|
|
553
|
-
code,
|
|
554
|
-
provider
|
|
555
|
-
}));
|
|
556
|
-
return;
|
|
557
|
-
}
|
|
558
|
-
let posted;
|
|
559
|
-
if (method === "POST" && signed && request.headers.origin === apiOrigin) {
|
|
560
|
-
const body = await form(request);
|
|
561
|
-
posted = body;
|
|
562
|
-
const decision = body?.get("session_decision");
|
|
563
|
-
if (body && decision !== null && decision !== void 0) {
|
|
564
|
-
const code = body.get("user_code") ?? "";
|
|
565
|
-
if (body.get("csrf") !== options.authorize.csrf(signed.hash, "device")) {
|
|
566
|
-
page(response, 403, devicePage({
|
|
567
|
-
code: "",
|
|
568
|
-
provider,
|
|
569
|
-
message: "This form must be sent from this page."
|
|
570
|
-
}));
|
|
571
|
-
return;
|
|
572
|
-
}
|
|
573
|
-
const approve = decision === "approve";
|
|
574
|
-
const decided = auth.decideFor({
|
|
575
|
-
code,
|
|
576
|
-
approve,
|
|
577
|
-
accountId: signed.accountId
|
|
578
|
-
});
|
|
579
|
-
page(response, decided.ok ? 200 : 400, devicePage({
|
|
580
|
-
code,
|
|
581
|
-
provider,
|
|
582
|
-
...decided.ok ? {
|
|
583
|
-
done: true,
|
|
584
|
-
message: approve ? "The machine is linked to your account." : "The sign-in was refused."
|
|
585
|
-
} : { message: decided.reason }
|
|
586
|
-
}));
|
|
587
|
-
return;
|
|
588
|
-
}
|
|
589
|
-
}
|
|
590
|
-
if (method === "POST") {
|
|
591
|
-
if (request.headers.origin !== apiOrigin) {
|
|
592
|
-
page(response, 403, devicePage({
|
|
593
|
-
code: "",
|
|
594
|
-
provider,
|
|
595
|
-
message: "This form must be sent from this page."
|
|
596
|
-
}));
|
|
597
|
-
return;
|
|
598
|
-
}
|
|
599
|
-
const body = posted ?? await form(request);
|
|
600
|
-
const code = body?.get("user_code") ?? "";
|
|
601
|
-
const name = (body?.get("name") ?? "").trim().slice(0, 64);
|
|
602
|
-
if (!body || !provider || !await devFormOffered() || body.get("provider") !== provider.id || name === "") {
|
|
603
|
-
page(response, 400, devicePage({
|
|
604
|
-
code,
|
|
605
|
-
provider,
|
|
606
|
-
message: "Enter the code and your name."
|
|
607
|
-
}));
|
|
608
|
-
return;
|
|
609
|
-
}
|
|
610
|
-
const approve = body.get("decision") === "approve";
|
|
611
|
-
const pending = auth.pendingCode(code);
|
|
612
|
-
if (!pending.ok) {
|
|
613
|
-
page(response, 400, devicePage({
|
|
614
|
-
code,
|
|
615
|
-
provider,
|
|
616
|
-
message: pending.reason
|
|
617
|
-
}));
|
|
618
|
-
return;
|
|
619
|
-
}
|
|
620
|
-
const identity = {
|
|
621
|
-
provider: provider.id,
|
|
622
|
-
subject: name.toLowerCase(),
|
|
623
|
-
name
|
|
624
|
-
};
|
|
625
|
-
let decided;
|
|
626
|
-
if (!approve) decided = auth.decide({
|
|
627
|
-
code,
|
|
628
|
-
approve: false,
|
|
629
|
-
identity
|
|
630
|
-
});
|
|
631
|
-
else {
|
|
632
|
-
const account = await auth.resolveAccount(identity, 0);
|
|
633
|
-
if (account.kind !== "account") {
|
|
634
|
-
const reason = account.kind === "unavailable" ? "Sign-in is unavailable for a moment; try again shortly." : account.kind === "refused" ? account.message : account.kind === "suspended" ? "This account is suspended." : "This server asks for a step before a first sign-in, which the development sign-in can't take.";
|
|
635
|
-
page(response, account.kind === "unavailable" ? 503 : 403, devicePage({
|
|
636
|
-
code,
|
|
637
|
-
provider,
|
|
638
|
-
message: reason
|
|
639
|
-
}));
|
|
640
|
-
return;
|
|
641
|
-
}
|
|
642
|
-
decided = auth.decideFor({
|
|
643
|
-
code,
|
|
644
|
-
approve: true,
|
|
645
|
-
accountId: account.accountId
|
|
646
|
-
});
|
|
647
|
-
}
|
|
648
|
-
if (!decided.ok) {
|
|
649
|
-
page(response, 400, devicePage({
|
|
650
|
-
code,
|
|
651
|
-
provider,
|
|
652
|
-
message: decided.reason
|
|
653
|
-
}));
|
|
654
|
-
return;
|
|
655
|
-
}
|
|
656
|
-
page(response, 200, devicePage({
|
|
657
|
-
code,
|
|
658
|
-
provider,
|
|
659
|
-
done: true,
|
|
660
|
-
message: approve ? "The machine is linked to your account." : "The sign-in was refused."
|
|
661
|
-
}));
|
|
662
|
-
return;
|
|
663
|
-
}
|
|
664
|
-
}
|
|
665
|
-
if (path === "/mcp" && options.mcp) {
|
|
666
|
-
const who = await bearer(request, "mcp");
|
|
667
|
-
const challenge = `Bearer resource_metadata="${apiOrigin}/.well-known/oauth-protected-resource/mcp"`;
|
|
668
|
-
if (!who) {
|
|
669
|
-
send(response, 401, {
|
|
670
|
-
error: "invalid_token",
|
|
671
|
-
error_description: "Sign in to use Mostra here."
|
|
672
|
-
}, { "www-authenticate": challenge });
|
|
673
|
-
return;
|
|
674
|
-
}
|
|
675
|
-
if ("refused" in who) {
|
|
676
|
-
send(response, 403, who.refused);
|
|
677
|
-
return;
|
|
678
|
-
}
|
|
679
|
-
if (!who.scope.split(" ").includes("mostra")) {
|
|
680
|
-
send(response, 403, {
|
|
681
|
-
error: "insufficient_scope",
|
|
682
|
-
error_description: "The token lacks the mostra scope."
|
|
683
|
-
}, { "www-authenticate": `${challenge}, error="insufficient_scope", scope="mostra"` });
|
|
684
|
-
return;
|
|
685
|
-
}
|
|
686
|
-
await options.mcp.handle(request, response, who);
|
|
687
|
-
return;
|
|
688
|
-
}
|
|
689
|
-
const file = /^\/files\/([0-9a-f]{64})$/.exec(path);
|
|
690
|
-
if (file && method === "PUT") {
|
|
691
|
-
await upload(request, response, file[1]);
|
|
692
|
-
return;
|
|
693
|
-
}
|
|
694
|
-
send(response, 404, {
|
|
695
|
-
code: "MOSTRA_HYGIENE_NOT_SERVED",
|
|
696
|
-
message: "Nothing is served at this path."
|
|
697
|
-
});
|
|
698
|
-
},
|
|
699
|
-
upgrade(request, socket, head, path) {
|
|
700
|
-
const refuse = (status, text, extra = "") => {
|
|
701
|
-
socket.end(`HTTP/1.1 ${status} ${text}\r\nconnection: close\r\ncontent-length: 0\r\n${extra}\r\n`);
|
|
702
|
-
};
|
|
703
|
-
if (path !== "/host") {
|
|
704
|
-
refuse(404, "Not Found");
|
|
705
|
-
return;
|
|
706
|
-
}
|
|
707
|
-
bearer(request, "host").then((who) => upgradeFor(who), (error) => {
|
|
708
|
-
log.error("binding.auth_failed", { error });
|
|
709
|
-
refuse(503, "Service Unavailable");
|
|
710
|
-
});
|
|
711
|
-
const upgradeFor = (who) => {
|
|
712
|
-
if (who && "refused" in who) {
|
|
713
|
-
refuse(403, "Forbidden");
|
|
714
|
-
return;
|
|
715
|
-
}
|
|
716
|
-
if (!who) {
|
|
717
|
-
refuse(401, "Unauthorized", `www-authenticate: Bearer resource_metadata="${apiOrigin}/.well-known/oauth-protected-resource/host"\r\n`);
|
|
718
|
-
return;
|
|
719
|
-
}
|
|
720
|
-
options.home(who.homeId).then((home) => {
|
|
721
|
-
sockets.handleUpgrade(request, socket, head, (ws) => {
|
|
722
|
-
bindings.add(ws);
|
|
723
|
-
bindingHomes.set(ws, who.homeId);
|
|
724
|
-
let expiresAt = who.expiresAt;
|
|
725
|
-
const attributes = {
|
|
726
|
-
accountId: who.accountId,
|
|
727
|
-
grantId: who.grantId,
|
|
728
|
-
homeId: who.homeId,
|
|
729
|
-
linkId: who.linkId,
|
|
730
|
-
replaceToken: (next) => {
|
|
731
|
-
expiresAt = next;
|
|
732
|
-
}
|
|
733
|
-
};
|
|
734
|
-
const watch = setInterval(() => {
|
|
735
|
-
if (Date.now() >= expiresAt) {
|
|
736
|
-
log.info("binding.token_expired", { home: who.homeId });
|
|
737
|
-
ws.close(4401, "token expired");
|
|
738
|
-
} else if (who.grantId.startsWith("credential:")) bearer(request, "host").then((still) => {
|
|
739
|
-
if (!still || "refused" in still) {
|
|
740
|
-
log.info("binding.credential_revoked", { home: who.homeId });
|
|
741
|
-
ws.close(4403, "credential revoked");
|
|
742
|
-
} else expiresAt = still.expiresAt;
|
|
743
|
-
}, () => void 0);
|
|
744
|
-
else if (!auth.grantLive(who.grantId)) {
|
|
745
|
-
log.info("binding.grant_revoked", { home: who.homeId });
|
|
746
|
-
ws.close(4403, "grant revoked");
|
|
747
|
-
} else standing(who).then((refused) => {
|
|
748
|
-
if (refused) {
|
|
749
|
-
log.info("binding.account_suspended", { home: who.homeId });
|
|
750
|
-
ws.close(4403, "account suspended");
|
|
751
|
-
}
|
|
752
|
-
}, () => void 0);
|
|
753
|
-
}, Math.min(GRANT_RECHECK_MS, options.recheckMs ?? GRANT_RECHECK_MS));
|
|
754
|
-
watch.unref();
|
|
755
|
-
ws.once("close", () => {
|
|
756
|
-
clearInterval(watch);
|
|
757
|
-
bindings.delete(ws);
|
|
758
|
-
bindingHomes.delete(ws);
|
|
759
|
-
});
|
|
760
|
-
ws.on("message", () => {
|
|
761
|
-
options.touch(who.homeId);
|
|
762
|
-
options.message?.(who.homeId);
|
|
763
|
-
});
|
|
764
|
-
serveWebSocket(home.protocol, ws, {
|
|
765
|
-
attributes,
|
|
766
|
-
log
|
|
767
|
-
});
|
|
768
|
-
log.info("binding.opened", {
|
|
769
|
-
home: who.homeId,
|
|
770
|
-
link: who.linkId
|
|
771
|
-
});
|
|
772
|
-
});
|
|
773
|
-
}, (error) => {
|
|
774
|
-
log.error("binding.home_failed", {
|
|
775
|
-
home: who.homeId,
|
|
776
|
-
error
|
|
777
|
-
});
|
|
778
|
-
refuse(503, "Service Unavailable");
|
|
779
|
-
});
|
|
780
|
-
};
|
|
781
|
-
},
|
|
782
|
-
closeHome(homeId) {
|
|
783
|
-
for (const [ws, home] of bindingHomes) if (home === homeId) ws.close(4403, "home unavailable");
|
|
784
|
-
},
|
|
785
|
-
close() {
|
|
786
|
-
for (const ws of bindings) ws.terminate();
|
|
787
|
-
sockets.close();
|
|
788
|
-
}
|
|
789
|
-
};
|
|
790
|
-
}
|
|
791
|
-
//#endregion
|
|
792
|
-
//#region src/server/clients.ts
|
|
793
|
-
/** An address as a number (IPv4 in 32 bits, IPv6 in 128), or `undefined` when it isn't one. */
|
|
794
|
-
function addressBits(address) {
|
|
795
|
-
let text = address.trim();
|
|
796
|
-
if (text.startsWith("[") && text.endsWith("]")) text = text.slice(1, -1);
|
|
797
|
-
const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(text);
|
|
798
|
-
if (mapped) text = mapped[1];
|
|
799
|
-
if (isIPv4(text)) return {
|
|
800
|
-
v6: false,
|
|
801
|
-
bits: text.split(".").map(Number).reduce((sum, part) => sum << 8n | BigInt(part), 0n)
|
|
802
|
-
};
|
|
803
|
-
if (!isIPv6(text)) return void 0;
|
|
804
|
-
const zone = text.indexOf("%");
|
|
805
|
-
if (zone !== -1) text = text.slice(0, zone);
|
|
806
|
-
const last = text.slice(text.lastIndexOf(":") + 1);
|
|
807
|
-
if (last.includes(".")) {
|
|
808
|
-
if (!isIPv4(last)) return void 0;
|
|
809
|
-
const parts = last.split(".").map(Number);
|
|
810
|
-
const high = (parts[0] << 8 | parts[1]).toString(16);
|
|
811
|
-
const low = (parts[2] << 8 | parts[3]).toString(16);
|
|
812
|
-
text = `${text.slice(0, -last.length)}${high}:${low}`;
|
|
813
|
-
}
|
|
814
|
-
const [head, tail] = text.split("::");
|
|
815
|
-
const left = head === "" ? [] : head.split(":");
|
|
816
|
-
const right = tail === void 0 ? [] : tail === "" ? [] : tail.split(":");
|
|
817
|
-
const groups = tail === void 0 ? left : [
|
|
818
|
-
...left,
|
|
819
|
-
...new Array(8 - left.length - right.length).fill("0"),
|
|
820
|
-
...right
|
|
821
|
-
];
|
|
822
|
-
if (groups.length !== 8) return void 0;
|
|
823
|
-
return {
|
|
824
|
-
v6: true,
|
|
825
|
-
bits: groups.reduce((sum, group) => sum << 16n | BigInt(Number.parseInt(group, 16)), 0n)
|
|
826
|
-
};
|
|
827
|
-
}
|
|
828
|
-
function parseRange(text) {
|
|
829
|
-
const [address, prefixText] = text.split("/");
|
|
830
|
-
const found = addressBits(address);
|
|
831
|
-
if (!found) return void 0;
|
|
832
|
-
const width = found.v6 ? 128 : 32;
|
|
833
|
-
const prefix = prefixText === void 0 ? width : Number(prefixText);
|
|
834
|
-
if (!Number.isInteger(prefix) || prefix < 0 || prefix > width) return void 0;
|
|
835
|
-
return {
|
|
836
|
-
v6: found.v6,
|
|
837
|
-
bits: found.bits,
|
|
838
|
-
prefix
|
|
839
|
-
};
|
|
840
|
-
}
|
|
841
|
-
function inRange(range, address) {
|
|
842
|
-
if (range.v6 !== address.v6) return false;
|
|
843
|
-
const shift = (range.v6 ? 128n : 32n) - BigInt(range.prefix);
|
|
844
|
-
return range.bits >> shift === address.bits >> shift;
|
|
845
|
-
}
|
|
846
|
-
/** Whether every entry of `trustedProxies` is an address or a CIDR block. */
|
|
847
|
-
function validProxies(entries) {
|
|
848
|
-
return entries.find((entry) => parseRange(entry) === void 0);
|
|
849
|
-
}
|
|
850
|
-
/** Builds the resolver; an entry that isn't an address or a block is ignored (checked at start). */
|
|
851
|
-
function clientAddresses(options) {
|
|
852
|
-
const proxies = (options.trustedProxies ?? []).map(parseRange).filter((range) => range !== void 0);
|
|
853
|
-
const trusted = (address) => {
|
|
854
|
-
const bits = addressBits(address);
|
|
855
|
-
return bits !== void 0 && proxies.some((range) => inRange(range, bits));
|
|
856
|
-
};
|
|
857
|
-
const ipv6Prefix = options.ipv6Prefix ?? 64;
|
|
858
|
-
const seen = /* @__PURE__ */ new WeakMap();
|
|
859
|
-
return {
|
|
860
|
-
of(incoming) {
|
|
861
|
-
if (seen.has(incoming)) return seen.get(incoming);
|
|
862
|
-
const peer = incoming.socket.remoteAddress;
|
|
863
|
-
let client = peer;
|
|
864
|
-
if (peer !== void 0 && trusted(peer)) {
|
|
865
|
-
const header = incoming.headers["x-forwarded-for"];
|
|
866
|
-
const entries = (Array.isArray(header) ? header.join(",") : header ?? "").split(",").map((entry) => entry.trim()).filter((entry) => entry !== "");
|
|
867
|
-
for (let index = entries.length - 1; index >= 0; index--) {
|
|
868
|
-
const entry = entries[index];
|
|
869
|
-
if (addressBits(entry) === void 0) break;
|
|
870
|
-
client = entry;
|
|
871
|
-
if (!trusted(entry)) break;
|
|
872
|
-
}
|
|
873
|
-
}
|
|
874
|
-
seen.set(incoming, client);
|
|
875
|
-
return client;
|
|
876
|
-
},
|
|
877
|
-
keyOf(address) {
|
|
878
|
-
if (address === void 0) return "unknown";
|
|
879
|
-
const bits = addressBits(address);
|
|
880
|
-
if (!bits) return `other:${address}`;
|
|
881
|
-
if (!bits.v6) return `v4:${bits.bits.toString(16)}`;
|
|
882
|
-
const shift = 128n - BigInt(ipv6Prefix);
|
|
883
|
-
return `v6:${(bits.bits >> shift).toString(16)}/${ipv6Prefix}`;
|
|
884
|
-
}
|
|
885
|
-
};
|
|
886
|
-
}
|
|
887
|
-
/**
|
|
888
|
-
* A token-bucket rate limiter over keys, in memory, bounded in the keys it keeps: each key holds up
|
|
889
|
-
* to `count` tokens and earns them back at `count` per `perMs`, so a burst of `count` passes and
|
|
890
|
-
* the sustained rate is exactly the rate.
|
|
891
|
-
*/
|
|
892
|
-
var RateLimiter = class {
|
|
893
|
-
#buckets = /* @__PURE__ */ new Map();
|
|
894
|
-
#now;
|
|
895
|
-
#maxKeys;
|
|
896
|
-
constructor(options = {}) {
|
|
897
|
-
this.#now = options.now ?? (() => Date.now());
|
|
898
|
-
this.#maxKeys = options.maxKeys ?? 1e5;
|
|
899
|
-
}
|
|
900
|
-
/** A key's bucket, refilled to now and marked most recently used, so the bound drops the least. */
|
|
901
|
-
#bucket(key, rate, now) {
|
|
902
|
-
const perToken = rate.perMs / rate.count;
|
|
903
|
-
let bucket = this.#buckets.get(key);
|
|
904
|
-
if (bucket) {
|
|
905
|
-
bucket.tokens = Math.min(rate.count, bucket.tokens + (now - bucket.at) / perToken);
|
|
906
|
-
bucket.at = now;
|
|
907
|
-
this.#buckets.delete(key);
|
|
908
|
-
} else {
|
|
909
|
-
if (this.#buckets.size >= this.#maxKeys) this.#buckets.delete(this.#buckets.keys().next().value);
|
|
910
|
-
bucket = {
|
|
911
|
-
tokens: rate.count,
|
|
912
|
-
at: now
|
|
913
|
-
};
|
|
914
|
-
}
|
|
915
|
-
this.#buckets.set(key, bucket);
|
|
916
|
-
return bucket;
|
|
917
|
-
}
|
|
918
|
-
/** How long until every bucket holds a token: 0 when they all do now. */
|
|
919
|
-
#wait(wanted, now) {
|
|
920
|
-
let waitMs = 0;
|
|
921
|
-
const buckets = wanted.map(({ key, rate }) => {
|
|
922
|
-
const bucket = this.#bucket(key, rate, now);
|
|
923
|
-
if (bucket.tokens < 1) waitMs = Math.max(waitMs, (1 - bucket.tokens) * (rate.perMs / rate.count));
|
|
924
|
-
return bucket;
|
|
925
|
-
});
|
|
926
|
-
return {
|
|
927
|
-
waitMs,
|
|
928
|
-
buckets
|
|
929
|
-
};
|
|
930
|
-
}
|
|
931
|
-
/**
|
|
932
|
-
* Takes one token under `key` when there is one. Without one, nothing is taken and the answer
|
|
933
|
-
* says when to try again, in whole seconds (`Retry-After`).
|
|
934
|
-
*/
|
|
935
|
-
take(key, rate) {
|
|
936
|
-
return this.takeAll([{
|
|
937
|
-
key,
|
|
938
|
-
rate
|
|
939
|
-
}]);
|
|
940
|
-
}
|
|
941
|
-
/**
|
|
942
|
-
* Gives back the token `takeAll` took under every key, as far as each bucket's size: an attempt
|
|
943
|
-
* someone refused after the rates admitted it (the operator's `limits`) costs nothing (second
|
|
944
|
-
* Fable review of WP-30, 2).
|
|
254
|
+
* Gives back the token `takeAll` took under every key, as far as each bucket's size: an attempt
|
|
255
|
+
* someone refused after the rates admitted it (the operator's `limits`) costs nothing (second
|
|
256
|
+
* Fable review of WP-30, 2).
|
|
945
257
|
*/
|
|
946
258
|
refundAll(wanted) {
|
|
947
259
|
const now = this.#now();
|
|
@@ -994,6 +306,11 @@ const Origin = z.string().refine((value) => {
|
|
|
994
306
|
}
|
|
995
307
|
}, { message: "must be an https: origin (http: only on loopback), with no path" });
|
|
996
308
|
/**
|
|
309
|
+
* A name or a short line a server's pages show (D171): 1 to 64 characters with no control,
|
|
310
|
+
* format or separator characters, as `verifierLabel` holds labels, so one can't read as another.
|
|
311
|
+
*/
|
|
312
|
+
const PageName = z.string().min(1).max(64).refine((value) => value.trim() !== "" && !/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(value), { message: "must be 1 to 64 characters with no control or format characters" });
|
|
313
|
+
/**
|
|
997
314
|
* The label a configured provider's verified names carry on a hosted page's sender line ("verified
|
|
998
315
|
* with GitHub"): its `label`, else GitHub's name or its ID; none for the development provider, which
|
|
999
316
|
* takes the typed name on trust (D161). Recorded on each identity the provider links (MT-03).
|
|
@@ -1065,7 +382,27 @@ const Config = z.strictObject({
|
|
|
1065
382
|
homes: z.strictObject({ idleCloseMinutes: z.number().positive().optional() }).optional(),
|
|
1066
383
|
framing: z.strictObject({ frameAncestors: z.literal("'none'") }).optional(),
|
|
1067
384
|
operator: z.string().optional(),
|
|
1068
|
-
chatHosts: z.record(z.string(), z.unknown()).optional()
|
|
385
|
+
chatHosts: z.record(z.string(), z.unknown()).optional(),
|
|
386
|
+
appearance: z.strictObject({
|
|
387
|
+
theme: z.enum(["studio", "mostra"]).optional(),
|
|
388
|
+
name: PageName.nullable().optional(),
|
|
389
|
+
logo: z.strictObject({
|
|
390
|
+
file: z.string().regex(/\.(svg|png|webp)$/i, { message: "must be an .svg, .png or .webp file" }),
|
|
391
|
+
alt: PageName,
|
|
392
|
+
width: z.int().min(1).max(400),
|
|
393
|
+
height: z.int().min(1).max(120)
|
|
394
|
+
}).optional(),
|
|
395
|
+
stageLine: PageName.optional(),
|
|
396
|
+
default: z.enum([
|
|
397
|
+
"system",
|
|
398
|
+
"light",
|
|
399
|
+
"dark"
|
|
400
|
+
]).optional(),
|
|
401
|
+
footer: z.array(z.strictObject({
|
|
402
|
+
href: z.string().refine((href) => safeHref(href) !== void 0, { message: "must be an https: address or a path of this server" }),
|
|
403
|
+
text: PageName
|
|
404
|
+
})).max(6).optional()
|
|
405
|
+
}).optional()
|
|
1069
406
|
});
|
|
1070
407
|
/** The configuration keys, and the variable each also comes from. */
|
|
1071
408
|
const KEYS = Object.keys(Config.shape);
|
|
@@ -1756,768 +1093,1612 @@ function forbiddenAddress(address) {
|
|
|
1756
1093
|
}
|
|
1757
1094
|
return (g0 & 65472) === 65152 || (g0 & 65024) === 64512 || (g0 & 65280) === 65280 || g0 === 100 && g1 === 65435 || g0 === 8194 || g0 === 8193 && g1 === 0 || g0 === 8193 && g1 === 3512 || g0 === 256 && g1 === 0 && g2 === 0 && g3 === 0;
|
|
1758
1095
|
}
|
|
1759
|
-
/** Whether a redirect URI a request names is one the client's list allows. */
|
|
1760
|
-
function redirectAllowed(registered, asked) {
|
|
1761
|
-
if (registered.includes(asked)) return true;
|
|
1762
|
-
let url;
|
|
1763
|
-
try {
|
|
1764
|
-
url = new URL(asked);
|
|
1765
|
-
} catch {
|
|
1766
|
-
return false;
|
|
1767
|
-
}
|
|
1768
|
-
if (!(url.protocol === "http:" && (url.hostname === "127.0.0.1" || url.hostname === "[::1]" || url.hostname === "localhost"))) return false;
|
|
1769
|
-
return registered.some((entry) => {
|
|
1770
|
-
try {
|
|
1771
|
-
const known = new URL(entry);
|
|
1772
|
-
return known.protocol === "http:" && known.hostname === url.hostname && known.pathname === url.pathname && known.search === url.search;
|
|
1773
|
-
} catch {
|
|
1774
|
-
return false;
|
|
1096
|
+
/** Whether a redirect URI a request names is one the client's list allows. */
|
|
1097
|
+
function redirectAllowed(registered, asked) {
|
|
1098
|
+
if (registered.includes(asked)) return true;
|
|
1099
|
+
let url;
|
|
1100
|
+
try {
|
|
1101
|
+
url = new URL(asked);
|
|
1102
|
+
} catch {
|
|
1103
|
+
return false;
|
|
1104
|
+
}
|
|
1105
|
+
if (!(url.protocol === "http:" && (url.hostname === "127.0.0.1" || url.hostname === "[::1]" || url.hostname === "localhost"))) return false;
|
|
1106
|
+
return registered.some((entry) => {
|
|
1107
|
+
try {
|
|
1108
|
+
const known = new URL(entry);
|
|
1109
|
+
return known.protocol === "http:" && known.hostname === url.hostname && known.pathname === url.pathname && known.search === url.search;
|
|
1110
|
+
} catch {
|
|
1111
|
+
return false;
|
|
1112
|
+
}
|
|
1113
|
+
});
|
|
1114
|
+
}
|
|
1115
|
+
/** Whether a redirect URI may be registered at all: https, or http on a loopback name. */
|
|
1116
|
+
function redirectRegistrable(uri) {
|
|
1117
|
+
try {
|
|
1118
|
+
const url = new URL(uri);
|
|
1119
|
+
if (url.hash !== "") return false;
|
|
1120
|
+
if (url.protocol === "https:") return true;
|
|
1121
|
+
return url.protocol === "http:" && (url.hostname === "127.0.0.1" || url.hostname === "[::1]" || url.hostname === "localhost");
|
|
1122
|
+
} catch {
|
|
1123
|
+
return false;
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
/** Whether a client ID names a metadata document: an https URL with a path. */
|
|
1127
|
+
function metadataClientId(clientId) {
|
|
1128
|
+
try {
|
|
1129
|
+
const url = new URL(clientId);
|
|
1130
|
+
return url.protocol === "https:" && url.pathname.length > 1 && url.hash === "" ? url : void 0;
|
|
1131
|
+
} catch {
|
|
1132
|
+
return;
|
|
1133
|
+
}
|
|
1134
|
+
}
|
|
1135
|
+
/** The loopback addresses a test's metadata origin may resolve to (`MOSTRA_TEST_CIMD_ORIGIN`). */
|
|
1136
|
+
const LOOPBACK = /* @__PURE__ */ new Set(["127.0.0.1", "::1"]);
|
|
1137
|
+
/** Builds the clients over the directory. */
|
|
1138
|
+
function createClients(options) {
|
|
1139
|
+
const { directory, log } = options;
|
|
1140
|
+
const now = options.now ?? (() => Date.now());
|
|
1141
|
+
const fetched = /* @__PURE__ */ new Map();
|
|
1142
|
+
const testOrigin = options.env["MOSTRA_TEST_CIMD_ORIGIN"];
|
|
1143
|
+
const sweep = () => {
|
|
1144
|
+
directory.write((db) => db.run("DELETE FROM oauth_client WHERE kind = 'registered' AND COALESCE(last_used_at, created_at) < ? AND id NOT IN (SELECT client_id FROM \"grant\" WHERE revoked_at IS NULL)", (/* @__PURE__ */ new Date(now() - UNUSED_CLIENT_MS)).toISOString()));
|
|
1145
|
+
};
|
|
1146
|
+
/** Fetches a document from a checked public address, with no redirect, bounded. */
|
|
1147
|
+
const fetchDocument = (url) => new Promise((resolve, reject) => {
|
|
1148
|
+
const test = testOrigin !== void 0 && url.origin === testOrigin.replace(/^http:/, "https:");
|
|
1149
|
+
const pinned = (hostname, options, callback) => {
|
|
1150
|
+
lookup(hostname, {
|
|
1151
|
+
all: true,
|
|
1152
|
+
verbatim: true
|
|
1153
|
+
}).then((addresses) => {
|
|
1154
|
+
if (addresses.length === 0) throw new Error("no address");
|
|
1155
|
+
for (const found of addresses) if (!(test && LOOPBACK.has(found.address)) && forbiddenAddress(found.address)) throw new Error(`the name resolves to a non-public address (${found.address})`);
|
|
1156
|
+
if (options.all === true) {
|
|
1157
|
+
callback(null, addresses);
|
|
1158
|
+
return;
|
|
1159
|
+
}
|
|
1160
|
+
const chosen = addresses[0];
|
|
1161
|
+
callback(null, chosen.address, chosen.family);
|
|
1162
|
+
}).catch((error) => callback(error, "", 0));
|
|
1163
|
+
};
|
|
1164
|
+
const literal = isIP(url.hostname.replace(/^\[|\]$/g, ""));
|
|
1165
|
+
if (!test && literal !== 0 && forbiddenAddress(url.hostname.replace(/^\[|\]$/g, ""))) {
|
|
1166
|
+
reject(/* @__PURE__ */ new Error("the document's address isn't public"));
|
|
1167
|
+
return;
|
|
1168
|
+
}
|
|
1169
|
+
const target = test ? new URL(url.href.replace(/^https:/, "http:")) : url;
|
|
1170
|
+
const request$2 = (test ? request : request$1)(target, {
|
|
1171
|
+
method: "GET",
|
|
1172
|
+
headers: {
|
|
1173
|
+
accept: "application/json",
|
|
1174
|
+
"user-agent": "mostra-remote-server"
|
|
1175
|
+
},
|
|
1176
|
+
timeout: FETCH_TIMEOUT_MS,
|
|
1177
|
+
lookup: pinned
|
|
1178
|
+
}, (response) => {
|
|
1179
|
+
let size = 0;
|
|
1180
|
+
const chunks = [];
|
|
1181
|
+
response.on("data", (chunk) => {
|
|
1182
|
+
size += chunk.length;
|
|
1183
|
+
if (size > MAX_DOCUMENT_BYTES) {
|
|
1184
|
+
request$2.destroy(/* @__PURE__ */ new Error("the document is larger than 64 KiB"));
|
|
1185
|
+
return;
|
|
1186
|
+
}
|
|
1187
|
+
chunks.push(chunk);
|
|
1188
|
+
});
|
|
1189
|
+
response.on("end", () => {
|
|
1190
|
+
const cache = String(response.headers["cache-control"] ?? "");
|
|
1191
|
+
const age = /max-age=(\d+)/.exec(cache);
|
|
1192
|
+
const noStore = /no-store|no-cache/.test(cache);
|
|
1193
|
+
resolve({
|
|
1194
|
+
status: response.statusCode ?? 0,
|
|
1195
|
+
body: Buffer.concat(chunks).toString("utf8"),
|
|
1196
|
+
maxAge: noStore ? 60 : Math.min(86400, Math.max(60, age ? Number(age[1]) : 300))
|
|
1197
|
+
});
|
|
1198
|
+
});
|
|
1199
|
+
response.on("error", reject);
|
|
1200
|
+
});
|
|
1201
|
+
const deadline = setTimeout(() => request$2.destroy(/* @__PURE__ */ new Error("the document took longer than 5 s")), FETCH_TIMEOUT_MS);
|
|
1202
|
+
request$2.on("close", () => clearTimeout(deadline));
|
|
1203
|
+
request$2.on("timeout", () => request$2.destroy(/* @__PURE__ */ new Error("the document took longer than 5 s")));
|
|
1204
|
+
request$2.on("error", reject);
|
|
1205
|
+
request$2.end();
|
|
1206
|
+
});
|
|
1207
|
+
const fromDocument = async (url) => {
|
|
1208
|
+
const cached = fetched.get(url.href);
|
|
1209
|
+
if (cached && cached.until > now()) return cached.client;
|
|
1210
|
+
let answer;
|
|
1211
|
+
try {
|
|
1212
|
+
answer = await fetchDocument(url);
|
|
1213
|
+
} catch (error) {
|
|
1214
|
+
log.warn("oauth.cimd_refused", {
|
|
1215
|
+
client: url.href,
|
|
1216
|
+
reason: error.message
|
|
1217
|
+
});
|
|
1218
|
+
return {
|
|
1219
|
+
error: "invalid_client",
|
|
1220
|
+
description: `The client's metadata document can't be fetched: ${error.message}.`
|
|
1221
|
+
};
|
|
1222
|
+
}
|
|
1223
|
+
if (answer.status !== 200) return {
|
|
1224
|
+
error: "invalid_client",
|
|
1225
|
+
description: `The client's metadata document answered ${answer.status}, not 200.`
|
|
1226
|
+
};
|
|
1227
|
+
let document;
|
|
1228
|
+
try {
|
|
1229
|
+
document = JSON.parse(answer.body);
|
|
1230
|
+
} catch {
|
|
1231
|
+
return {
|
|
1232
|
+
error: "invalid_client",
|
|
1233
|
+
description: "The client's metadata document isn't JSON."
|
|
1234
|
+
};
|
|
1235
|
+
}
|
|
1236
|
+
if (document.client_id !== url.href) return {
|
|
1237
|
+
error: "invalid_client",
|
|
1238
|
+
description: "The metadata document's client_id isn't its own URL."
|
|
1239
|
+
};
|
|
1240
|
+
const redirects = Array.isArray(document.redirect_uris) ? document.redirect_uris.filter((uri) => typeof uri === "string" && redirectRegistrable(uri)) : [];
|
|
1241
|
+
if (redirects.length === 0) return {
|
|
1242
|
+
error: "invalid_client",
|
|
1243
|
+
description: "The metadata document names no usable redirect_uris."
|
|
1244
|
+
};
|
|
1245
|
+
const client = {
|
|
1246
|
+
id: url.href,
|
|
1247
|
+
kind: "metadata",
|
|
1248
|
+
name: typeof document.client_name === "string" && document.client_name.trim() !== "" ? document.client_name.trim().slice(0, 128) : url.hostname,
|
|
1249
|
+
redirectUris: redirects,
|
|
1250
|
+
unverified: true
|
|
1251
|
+
};
|
|
1252
|
+
fetched.set(url.href, {
|
|
1253
|
+
client,
|
|
1254
|
+
until: now() + answer.maxAge * 1e3
|
|
1255
|
+
});
|
|
1256
|
+
if (fetched.size > 1e3) fetched.delete(fetched.keys().next().value);
|
|
1257
|
+
directory.write((db) => db.run(`INSERT INTO oauth_client (id, kind, metadata_json, created_at) VALUES (?, 'metadata', ?, ?)
|
|
1258
|
+
ON CONFLICT (id) DO UPDATE SET metadata_json = excluded.metadata_json`, client.id, JSON.stringify({
|
|
1259
|
+
client_name: client.name,
|
|
1260
|
+
redirect_uris: client.redirectUris
|
|
1261
|
+
}), new Date(now()).toISOString()));
|
|
1262
|
+
return client;
|
|
1263
|
+
};
|
|
1264
|
+
const shellClientId = (shellOrigin) => `${shellOrigin}/_mostra/signin`;
|
|
1265
|
+
return {
|
|
1266
|
+
shellClientId,
|
|
1267
|
+
async find(clientId) {
|
|
1268
|
+
if (clientId === "mostra-cli") return {
|
|
1269
|
+
id: clientId,
|
|
1270
|
+
kind: "cli",
|
|
1271
|
+
name: "Mostra CLI",
|
|
1272
|
+
redirectUris: [],
|
|
1273
|
+
unverified: false
|
|
1274
|
+
};
|
|
1275
|
+
const origin = clientId.endsWith("/_mostra/signin") ? clientId.slice(0, -15) : void 0;
|
|
1276
|
+
if (origin !== void 0 && options.isShellOrigin(origin)) {
|
|
1277
|
+
directory.write((db) => db.run("INSERT OR IGNORE INTO oauth_client (id, kind, metadata_json, created_at) VALUES (?, 'shell', ?, ?)", clientId, JSON.stringify({ client_name: "Mostra" }), new Date(now()).toISOString()));
|
|
1278
|
+
return {
|
|
1279
|
+
id: clientId,
|
|
1280
|
+
kind: "shell",
|
|
1281
|
+
name: "Mostra",
|
|
1282
|
+
redirectUris: [`${origin}/_mostra/signin`],
|
|
1283
|
+
unverified: false
|
|
1284
|
+
};
|
|
1285
|
+
}
|
|
1286
|
+
const url = metadataClientId(clientId);
|
|
1287
|
+
if (url) return fromDocument(url);
|
|
1288
|
+
const row = directory.read((db) => db.get("SELECT metadata_json FROM oauth_client WHERE id = ? AND kind = 'registered'", clientId));
|
|
1289
|
+
if (!row) return {
|
|
1290
|
+
error: "invalid_client",
|
|
1291
|
+
description: "Unknown client."
|
|
1292
|
+
};
|
|
1293
|
+
const metadata = JSON.parse(row.metadata_json);
|
|
1294
|
+
return {
|
|
1295
|
+
id: clientId,
|
|
1296
|
+
kind: "registered",
|
|
1297
|
+
name: metadata.client_name ?? "An unnamed client",
|
|
1298
|
+
redirectUris: metadata.redirect_uris,
|
|
1299
|
+
unverified: true
|
|
1300
|
+
};
|
|
1301
|
+
},
|
|
1302
|
+
register(metadata) {
|
|
1303
|
+
sweep();
|
|
1304
|
+
const body = typeof metadata === "object" && metadata !== null ? metadata : {};
|
|
1305
|
+
const redirects = Array.isArray(body.redirect_uris) ? body.redirect_uris.filter((uri) => typeof uri === "string") : [];
|
|
1306
|
+
if (redirects.length === 0 || redirects.length > 10 || !redirects.every(redirectRegistrable)) return {
|
|
1307
|
+
error: "invalid_redirect_uri",
|
|
1308
|
+
description: "redirect_uris must list https: addresses, or http: on 127.0.0.1, [::1] or localhost."
|
|
1309
|
+
};
|
|
1310
|
+
if (body.token_endpoint_auth_method !== void 0 && body.token_endpoint_auth_method !== "none") return {
|
|
1311
|
+
error: "invalid_client_metadata",
|
|
1312
|
+
description: "This server registers public clients only (token_endpoint_auth_method none)."
|
|
1313
|
+
};
|
|
1314
|
+
const name = typeof body.client_name === "string" ? body.client_name.trim().slice(0, 128) : void 0;
|
|
1315
|
+
const id = `mcl_${randomBytes(16).toString("hex")}`;
|
|
1316
|
+
const at = new Date(now());
|
|
1317
|
+
directory.write((db) => db.run("INSERT INTO oauth_client (id, kind, metadata_json, created_at, last_used_at) VALUES (?, 'registered', ?, ?, ?)", id, JSON.stringify({
|
|
1318
|
+
client_name: name,
|
|
1319
|
+
redirect_uris: redirects
|
|
1320
|
+
}), at.toISOString(), at.toISOString()));
|
|
1321
|
+
log.info("oauth.client_registered", { client: id });
|
|
1322
|
+
return {
|
|
1323
|
+
client_id: id,
|
|
1324
|
+
client_id_issued_at: Math.floor(at.getTime() / 1e3),
|
|
1325
|
+
...name !== void 0 ? { client_name: name } : {},
|
|
1326
|
+
redirect_uris: redirects,
|
|
1327
|
+
token_endpoint_auth_method: "none",
|
|
1328
|
+
grant_types: ["authorization_code", "refresh_token"],
|
|
1329
|
+
response_types: ["code"]
|
|
1330
|
+
};
|
|
1331
|
+
},
|
|
1332
|
+
used(clientId) {
|
|
1333
|
+
directory.write((db) => db.run("UPDATE oauth_client SET last_used_at = ? WHERE id = ?", new Date(now()).toISOString(), clientId));
|
|
1334
|
+
}
|
|
1335
|
+
};
|
|
1336
|
+
}
|
|
1337
|
+
//#endregion
|
|
1338
|
+
//#region src/server/pages.ts
|
|
1339
|
+
/** Where a person's appearance switch posts on the API origin (D171). */
|
|
1340
|
+
const APPEARANCE_PATH = "/_mostra/appearance";
|
|
1341
|
+
/** Every word the API origin's pages say (D149: Mirza reviews them). */
|
|
1342
|
+
const API_PAGE_WORDS = {
|
|
1343
|
+
signInTitle: (name) => name ? `Sign in to ${name}` : "Sign in",
|
|
1344
|
+
signInLede: "Choose how to sign in.",
|
|
1345
|
+
continueWith: (label) => `Continue with ${label}`,
|
|
1346
|
+
noProviders: "This server has no sign-in set up yet, so nobody can sign in.",
|
|
1347
|
+
neverPassword: "You sign in with your provider. This server never sees your password.",
|
|
1348
|
+
devTitle: "Development sign-in",
|
|
1349
|
+
devNote: "This server signs people in with a development provider, which trusts the name you type. Use it only on a server you run for yourself or for tests.",
|
|
1350
|
+
yourName: "Your name",
|
|
1351
|
+
continue: "Continue",
|
|
1352
|
+
cantContinue: "Sign-in can't continue",
|
|
1353
|
+
deviceTitle: "Link this machine",
|
|
1354
|
+
deviceSignedInAs: (name) => html`Signed in as <strong>${name}</strong>.`,
|
|
1355
|
+
deviceWarning: "Approving links a machine to your account. That machine's Mostra can then host pages under your account and receives their answers. Continue only if you started this sign-in yourself, on that machine.",
|
|
1356
|
+
deviceCode: "The code that machine shows",
|
|
1357
|
+
approveMachine: "Approve this machine",
|
|
1358
|
+
refuse: "Refuse",
|
|
1359
|
+
deviceLinked: "The machine is linked to your account.",
|
|
1360
|
+
deviceRefused: "The sign-in was refused.",
|
|
1361
|
+
deviceClose: "You can close this page.",
|
|
1362
|
+
answerTitle: "Answer as yourself",
|
|
1363
|
+
answerAs: (who, owner) => `Continue as ${who} to answer ${owner}'s page?`,
|
|
1364
|
+
answerDetail: "They will see your name with your answers.",
|
|
1365
|
+
thisPerson: "this person",
|
|
1366
|
+
allowTitle: (client) => `Allow ${client}?`,
|
|
1367
|
+
asksToUse: (client, who) => html`${client} asks to use Mostra as <strong>${who}</strong>.`,
|
|
1368
|
+
unverifiedName: "a name the app gives itself, not checked",
|
|
1369
|
+
grants: ["Read, create and change your hosted pages", "Read their answers"],
|
|
1370
|
+
sendsBackTo: (host) => html`It will send you back to <strong>${host}</strong>.`,
|
|
1371
|
+
loopback: "That is a program on your own computer: continue only if you started this there.",
|
|
1372
|
+
allow: "Allow",
|
|
1373
|
+
cancel: "Cancel",
|
|
1374
|
+
yourAccount: "your account"
|
|
1375
|
+
};
|
|
1376
|
+
/** The marks of providers a person recognises, by provider ID. Others show their label alone. */
|
|
1377
|
+
const PROVIDER_ICONS = {
|
|
1378
|
+
github: html`<svg viewBox="0 0 16 16" aria-hidden="true"><path fill="currentColor" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"/></svg>`,
|
|
1379
|
+
google: html`<svg viewBox="0 0 18 18" aria-hidden="true"><path fill="#4285F4" d="M17.64 9.2c0-.64-.06-1.25-.16-1.84H9v3.48h4.84a4.14 4.14 0 0 1-1.8 2.72v2.26h2.92a8.78 8.78 0 0 0 2.68-6.62z"/><path fill="#34A853" d="M9 18c2.43 0 4.47-.8 5.96-2.18l-2.92-2.26c-.8.54-1.84.86-3.04.86-2.34 0-4.33-1.58-5.04-3.7H.96v2.33A9 9 0 0 0 9 18z"/><path fill="#FBBC05" d="M3.96 10.72A5.4 5.4 0 0 1 3.68 9c0-.6.1-1.18.28-1.72V4.95H.96A9 9 0 0 0 0 9c0 1.45.35 2.83.96 4.05l3-2.33z"/><path fill="#EA4335" d="M9 3.58c1.32 0 2.5.45 3.44 1.35l2.58-2.58A8.97 8.97 0 0 0 9 0 9 9 0 0 0 .96 4.95l3 2.33C4.67 5.16 6.66 3.58 9 3.58z"/></svg>`
|
|
1380
|
+
};
|
|
1381
|
+
/** Makes the API origin's pages from the server's own pages (its theme and name). */
|
|
1382
|
+
function createApiPages(server, name) {
|
|
1383
|
+
const W = API_PAGE_WORDS;
|
|
1384
|
+
const { pages } = server;
|
|
1385
|
+
const consentButtons = (approve) => actions(button(approve, {
|
|
1386
|
+
name: "decision",
|
|
1387
|
+
value: "approve",
|
|
1388
|
+
primary: true
|
|
1389
|
+
}), button(W.cancel, {
|
|
1390
|
+
name: "decision",
|
|
1391
|
+
value: "deny"
|
|
1392
|
+
}));
|
|
1393
|
+
return {
|
|
1394
|
+
name,
|
|
1395
|
+
signIn(request, providers, next, message) {
|
|
1396
|
+
const list = providers.map((provider, index) => linkButton(`/signin/${encodeURIComponent(provider.id)}/start?next=${encodeURIComponent(next)}`, W.continueWith(provider.label), {
|
|
1397
|
+
primary: index === 0,
|
|
1398
|
+
...PROVIDER_ICONS[provider.id] ? { icon: PROVIDER_ICONS[provider.id] } : {}
|
|
1399
|
+
}));
|
|
1400
|
+
return pages.render({
|
|
1401
|
+
kind: "task",
|
|
1402
|
+
title: W.signInTitle(name),
|
|
1403
|
+
lede: W.signInLede,
|
|
1404
|
+
body: html`${message ? alert(message) : ""}${list.length > 0 ? html`<div class="m-list">${list}</div>${fine(W.neverPassword)}` : alert(W.noProviders, "note")}`,
|
|
1405
|
+
...request
|
|
1406
|
+
});
|
|
1407
|
+
},
|
|
1408
|
+
developmentName(request, providerId, state) {
|
|
1409
|
+
return pages.render({
|
|
1410
|
+
kind: "task",
|
|
1411
|
+
title: W.devTitle,
|
|
1412
|
+
body: html`${alert(W.devNote, "note")}<form method="post" action="/signin/${providerId}/name"><input type="hidden" name="state" value="${state}">${field({
|
|
1413
|
+
label: W.yourName,
|
|
1414
|
+
name: "name",
|
|
1415
|
+
required: true,
|
|
1416
|
+
maxLength: 64,
|
|
1417
|
+
autocomplete: "name"
|
|
1418
|
+
})}${actions(button(W.continue, { primary: true }))}</form>`,
|
|
1419
|
+
...request
|
|
1420
|
+
});
|
|
1421
|
+
},
|
|
1422
|
+
problem(request, message) {
|
|
1423
|
+
return pages.render({
|
|
1424
|
+
kind: "notice",
|
|
1425
|
+
tone: "problem",
|
|
1426
|
+
title: W.cantContinue,
|
|
1427
|
+
body: html`<p>${message}</p>`,
|
|
1428
|
+
...request
|
|
1429
|
+
});
|
|
1430
|
+
},
|
|
1431
|
+
answerAs(request, form, who, owner) {
|
|
1432
|
+
return pages.render({
|
|
1433
|
+
kind: "task",
|
|
1434
|
+
title: W.answerTitle,
|
|
1435
|
+
lede: W.answerAs(who, owner ?? W.thisPerson),
|
|
1436
|
+
body: html`<p>${W.answerDetail}</p><form method="post" action="${form.action}"><input type="hidden" name="csrf" value="${form.csrf}">${consentButtons(W.continue)}</form>`,
|
|
1437
|
+
...request
|
|
1438
|
+
});
|
|
1439
|
+
},
|
|
1440
|
+
allow(request, form, client, who, redirectHost, loopback) {
|
|
1441
|
+
const clientName = client.unverified ? html`<strong>${client.name}</strong> <span class="m-hint">(${W.unverifiedName})</span>` : html`<strong>${client.name}</strong>`;
|
|
1442
|
+
return pages.render({
|
|
1443
|
+
kind: "task",
|
|
1444
|
+
title: W.allowTitle(client.name),
|
|
1445
|
+
lede: W.asksToUse(clientName, who),
|
|
1446
|
+
body: html`<ul class="m-grants">${W.grants.map((grant) => html`<li>${grant}</li>`)}</ul><p>${W.sendsBackTo(redirectHost)}</p>${loopback ? alert(W.loopback) : ""}<form method="post" action="${form.action}"><input type="hidden" name="csrf" value="${form.csrf}">${consentButtons(W.allow)}</form>`,
|
|
1447
|
+
...request
|
|
1448
|
+
});
|
|
1449
|
+
},
|
|
1450
|
+
deviceForm(request, options) {
|
|
1451
|
+
const signedIn = options.signedIn;
|
|
1452
|
+
const development = options.development;
|
|
1453
|
+
const form = signedIn ? html`<form method="post" action="/device"><input type="hidden" name="csrf" value="${signedIn.csrf}">${field({
|
|
1454
|
+
label: W.deviceCode,
|
|
1455
|
+
name: "user_code",
|
|
1456
|
+
value: options.code,
|
|
1457
|
+
required: true,
|
|
1458
|
+
code: true
|
|
1459
|
+
})}${actions(button(W.approveMachine, {
|
|
1460
|
+
name: "session_decision",
|
|
1461
|
+
value: "approve",
|
|
1462
|
+
primary: true
|
|
1463
|
+
}), button(W.refuse, {
|
|
1464
|
+
name: "session_decision",
|
|
1465
|
+
value: "deny"
|
|
1466
|
+
}))}</form>` : development ? html`<form method="post" action="/device">${field({
|
|
1467
|
+
label: W.deviceCode,
|
|
1468
|
+
name: "user_code",
|
|
1469
|
+
value: options.code,
|
|
1470
|
+
required: true,
|
|
1471
|
+
code: true
|
|
1472
|
+
})}${alert(W.devNote, "note")}${field({
|
|
1473
|
+
label: W.yourName,
|
|
1474
|
+
name: "name",
|
|
1475
|
+
required: true,
|
|
1476
|
+
maxLength: 64,
|
|
1477
|
+
autocomplete: "name"
|
|
1478
|
+
})}<input type="hidden" name="provider" value="${development.id}">${actions(button(W.approveMachine, {
|
|
1479
|
+
name: "decision",
|
|
1480
|
+
value: "approve",
|
|
1481
|
+
primary: true
|
|
1482
|
+
}), button(W.refuse, {
|
|
1483
|
+
name: "decision",
|
|
1484
|
+
value: "deny"
|
|
1485
|
+
}))}</form>` : alert(W.noProviders, "note");
|
|
1486
|
+
return pages.render({
|
|
1487
|
+
kind: "task",
|
|
1488
|
+
title: W.deviceTitle,
|
|
1489
|
+
...signedIn ? { lede: W.deviceSignedInAs(signedIn.name) } : {},
|
|
1490
|
+
body: html`${options.message ? alert(options.message) : ""}${alert(W.deviceWarning, "note")}${form}`,
|
|
1491
|
+
...request
|
|
1492
|
+
});
|
|
1493
|
+
},
|
|
1494
|
+
deviceDone(request, message) {
|
|
1495
|
+
return pages.render({
|
|
1496
|
+
kind: "notice",
|
|
1497
|
+
title: message,
|
|
1498
|
+
body: html`<p>${W.deviceClose}</p>`,
|
|
1499
|
+
...request
|
|
1500
|
+
});
|
|
1775
1501
|
}
|
|
1776
|
-
}
|
|
1502
|
+
};
|
|
1777
1503
|
}
|
|
1778
|
-
|
|
1779
|
-
|
|
1504
|
+
//#endregion
|
|
1505
|
+
//#region src/server/authorize.ts
|
|
1506
|
+
/**
|
|
1507
|
+
* The authorization server's pages on the API origin (INTERFACES §18.5, D165 items 8, 10):
|
|
1508
|
+
*
|
|
1509
|
+
* - `GET /oauth/authorize`: the authorization code flow with PKCE (S256) for MCP clients (Client
|
|
1510
|
+
* ID Metadata Documents, registered clients) and for each hosted shell's viewer sign-in. The
|
|
1511
|
+
* client and its redirect URI are checked before anything is redirected anywhere; an `iss`
|
|
1512
|
+
* parameter goes with every answer (RFC 9207).
|
|
1513
|
+
* - Sign-in through an identity provider (`/signin/<id>/start`, its `callback`), into a browser
|
|
1514
|
+
* session on the API origin only, never the user-content domain; the operator's first sign-in
|
|
1515
|
+
* steps (`/signin/return`).
|
|
1516
|
+
* - The server's own consent page (`/oauth/consent`), for every client an account hasn't
|
|
1517
|
+
* approved, never skipped because a provider skipped its own; for a page's sign-in it names
|
|
1518
|
+
* the page's sender instead, once per account and home.
|
|
1519
|
+
*
|
|
1520
|
+
* Every in-progress record (an authorization request, a provider sign-in, a first sign-in step)
|
|
1521
|
+
* is kept only as the SHA-256 of its handle, lives minutes, is used once, and is bound to the
|
|
1522
|
+
* browser that started it by a cookie of the API origin.
|
|
1523
|
+
*/
|
|
1524
|
+
/** How long an authorization request, a provider sign-in or a step waits. */
|
|
1525
|
+
const PENDING_MS = 9e5;
|
|
1526
|
+
/** How long a browser stays signed in to the API origin. */
|
|
1527
|
+
const SESSION_MS = 6048e5;
|
|
1528
|
+
/** At most this many first sign-in steps per sign-in (D167). */
|
|
1529
|
+
const MAX_STEPS = 3;
|
|
1530
|
+
/**
|
|
1531
|
+
* How long an identity provider's own calls may take (its authorization address, the code's
|
|
1532
|
+
* exchange): inside the 10 s every endpoint of the authorization server answers in (D165 item 10),
|
|
1533
|
+
* whether the provider is built in or the operator's.
|
|
1534
|
+
*/
|
|
1535
|
+
const PROVIDER_MS = 8e3;
|
|
1536
|
+
/** A provider's call, or a refusal once it took longer than {@link PROVIDER_MS}. */
|
|
1537
|
+
async function bounded(call, what) {
|
|
1538
|
+
let timer;
|
|
1780
1539
|
try {
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
return false;
|
|
1540
|
+
return await Promise.race([Promise.resolve().then(call), new Promise((_, reject) => {
|
|
1541
|
+
timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`${what} took too long`)), PROVIDER_MS);
|
|
1542
|
+
})]);
|
|
1543
|
+
} finally {
|
|
1544
|
+
clearTimeout(timer);
|
|
1787
1545
|
}
|
|
1788
1546
|
}
|
|
1789
|
-
/**
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1547
|
+
/**
|
|
1548
|
+
* Where a page answers and what its reader chose (their appearance, D171), from the request a
|
|
1549
|
+
* response answers.
|
|
1550
|
+
*/
|
|
1551
|
+
function pageRequest(response) {
|
|
1552
|
+
const request = response.req;
|
|
1553
|
+
const cookie = request?.headers.cookie;
|
|
1554
|
+
const chosen = cookie?.includes("mostra-appearance=") ? readAppearance(cookie) : void 0;
|
|
1555
|
+
return {
|
|
1556
|
+
...chosen ? { appearance: chosen } : {},
|
|
1557
|
+
path: request?.url ?? "/"
|
|
1558
|
+
};
|
|
1797
1559
|
}
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1560
|
+
const BASE = {
|
|
1561
|
+
"cache-control": "no-store",
|
|
1562
|
+
"cross-origin-resource-policy": "same-origin",
|
|
1563
|
+
"x-content-type-options": "nosniff",
|
|
1564
|
+
"x-frame-options": "DENY"
|
|
1565
|
+
};
|
|
1566
|
+
/** Builds the pages. */
|
|
1567
|
+
function createAuthorize(options) {
|
|
1568
|
+
const { apiOrigin, directory, auth, clients, operator, log, pages } = options;
|
|
1569
|
+
const at = (response) => pageRequest(response);
|
|
1803
1570
|
const now = options.now ?? (() => Date.now());
|
|
1804
|
-
const
|
|
1805
|
-
const
|
|
1806
|
-
const
|
|
1807
|
-
|
|
1571
|
+
const secure = apiOrigin.startsWith("https:");
|
|
1572
|
+
const sessionCookie = secure ? "__Host-mostra-signin" : "mostra-signin";
|
|
1573
|
+
const flowCookie = secure ? "__Host-mostra-flow" : "mostra-flow";
|
|
1574
|
+
const iso = (ms) => new Date(ms).toISOString();
|
|
1575
|
+
const token = () => randomBytes(32).toString("base64url");
|
|
1576
|
+
const cookies = (request) => {
|
|
1577
|
+
const found = /* @__PURE__ */ new Map();
|
|
1578
|
+
for (const part of (request.headers.cookie ?? "").split(";")) {
|
|
1579
|
+
const at = part.indexOf("=");
|
|
1580
|
+
if (at <= 0) continue;
|
|
1581
|
+
const name = part.slice(0, at).trim();
|
|
1582
|
+
if (!found.has(name)) found.set(name, part.slice(at + 1).trim());
|
|
1583
|
+
}
|
|
1584
|
+
return found;
|
|
1808
1585
|
};
|
|
1809
|
-
|
|
1810
|
-
const
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1586
|
+
const setCookie = (name, value, maxAgeS) => `${name}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAgeS}${secure ? "; Secure" : ""}`;
|
|
1587
|
+
const send = (response, status, html, extra = {}, formTargets = []) => {
|
|
1588
|
+
response.writeHead(status, {
|
|
1589
|
+
...BASE,
|
|
1590
|
+
"content-type": "text/html; charset=utf-8",
|
|
1591
|
+
"content-security-policy": themePageCsp(options.server.pages, "'none'", ["'self'", ...formTargets].join(" ")),
|
|
1592
|
+
"referrer-policy": "same-origin",
|
|
1593
|
+
...extra
|
|
1594
|
+
});
|
|
1595
|
+
response.end(html);
|
|
1596
|
+
};
|
|
1597
|
+
const redirect = (response, location, extra = {}) => {
|
|
1598
|
+
response.writeHead(303, {
|
|
1599
|
+
...BASE,
|
|
1600
|
+
location,
|
|
1601
|
+
"referrer-policy": "no-referrer",
|
|
1602
|
+
...extra
|
|
1603
|
+
});
|
|
1604
|
+
response.end();
|
|
1605
|
+
};
|
|
1606
|
+
const problem = (response, status, message) => send(response, status, pages.problem(at(response), message));
|
|
1607
|
+
const keep = (kind, handle, data) => directory.write((db) => {
|
|
1608
|
+
db.run("DELETE FROM signin WHERE expires_at < ?", iso(now()));
|
|
1609
|
+
db.run("INSERT INTO signin (hash, kind, data_json, expires_at) VALUES (?, ?, ?, ?)", hashSecret(handle), kind, JSON.stringify(data), iso(now() + PENDING_MS));
|
|
1610
|
+
});
|
|
1611
|
+
const read = (kind, handle) => directory.read((db) => {
|
|
1612
|
+
const row = db.get("SELECT data_json, expires_at FROM signin WHERE hash = ? AND kind = ?", hashSecret(handle), kind);
|
|
1613
|
+
return row && Date.parse(row.expires_at) > now() ? JSON.parse(row.data_json) : void 0;
|
|
1614
|
+
});
|
|
1615
|
+
const spend = (handle) => directory.write((db) => db.run("DELETE FROM signin WHERE hash = ?", hashSecret(handle)).changes > 0);
|
|
1616
|
+
const sessionAccount = (request) => {
|
|
1617
|
+
const value = cookies(request).get(sessionCookie);
|
|
1618
|
+
if (value === void 0 || !/^[A-Za-z0-9_-]{43}$/.test(value)) return void 0;
|
|
1619
|
+
const hash = hashSecret(value);
|
|
1620
|
+
const row = directory.read((db) => db.get(`SELECT s.account_id, s.expires_at, a.status FROM browser_session s
|
|
1621
|
+
JOIN account a ON a.id = s.account_id WHERE s.hash = ?`, hash));
|
|
1622
|
+
if (!row || Date.parse(row.expires_at) <= now() || row.status !== "active") return void 0;
|
|
1623
|
+
return {
|
|
1624
|
+
accountId: row.account_id,
|
|
1625
|
+
hash
|
|
1826
1626
|
};
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1627
|
+
};
|
|
1628
|
+
const startSession = (accountId) => {
|
|
1629
|
+
const value = token();
|
|
1630
|
+
directory.write((db) => db.run("INSERT INTO browser_session (hash, account_id, created_at, expires_at) VALUES (?, ?, ?, ?)", hashSecret(value), accountId, iso(now()), iso(now() + SESSION_MS)));
|
|
1631
|
+
return setCookie(sessionCookie, value, Math.floor(SESSION_MS / 1e3));
|
|
1632
|
+
};
|
|
1633
|
+
const csrf = (sessionHash, purpose) => createHash("sha256").update(`mostra csrf ${sessionHash} ${purpose}`).digest("base64url");
|
|
1634
|
+
/**
|
|
1635
|
+
* The label a provider's verified names carry (`IdentityProvider.verifies`, MT-03): text of 1 to
|
|
1636
|
+
* 64 characters, else none, since an operator's provider is checked as every operator answer is.
|
|
1637
|
+
*/
|
|
1638
|
+
const verifierOf = (provider) => {
|
|
1639
|
+
const raw = provider.verifies?.label;
|
|
1640
|
+
const label = verifierLabel(raw);
|
|
1641
|
+
if (label === void 0 && provider.verifies !== void 0) log.warn("signin.verifier_refused", { provider: provider.id });
|
|
1642
|
+
return label;
|
|
1643
|
+
};
|
|
1644
|
+
/** The providers now: configured ones, then the operator's (asked each time, D167). */
|
|
1645
|
+
const providers = async () => {
|
|
1646
|
+
const supplied = await operator.providers();
|
|
1647
|
+
const ids = new Set(options.providers.map((provider) => provider.id));
|
|
1648
|
+
return [...options.providers, ...supplied.filter((provider) => !ids.has(provider.id))];
|
|
1649
|
+
};
|
|
1650
|
+
/** The page listing the providers; each starts a sign-in that returns to `next`. */
|
|
1651
|
+
const signInPage = async (response, next, message) => {
|
|
1652
|
+
const list = await providers();
|
|
1653
|
+
send(response, 200, pages.signIn(at(response), list.map((provider) => ({
|
|
1654
|
+
id: provider.id,
|
|
1655
|
+
label: provider.label
|
|
1656
|
+
})), next, message));
|
|
1657
|
+
};
|
|
1658
|
+
/** Where a finished sign-in continues: an address of the API origin only. */
|
|
1659
|
+
const safeNext = (next) => next?.startsWith("/") && !next.startsWith("//") ? next : "/";
|
|
1660
|
+
/** A resolved identity: a session and on to `next`, a step, or why not. */
|
|
1661
|
+
const resolved = async (response, identity, verifiedBy, steps, flow, next) => {
|
|
1662
|
+
const account = await auth.resolveAccount(identity, steps, verifiedBy);
|
|
1663
|
+
if (account.kind === "unavailable") {
|
|
1664
|
+
problem(response, 503, "Sign-in is unavailable for a moment; try again shortly.");
|
|
1665
|
+
return;
|
|
1666
|
+
}
|
|
1667
|
+
if (account.kind === "refused") {
|
|
1668
|
+
problem(response, 403, account.message);
|
|
1669
|
+
return;
|
|
1670
|
+
}
|
|
1671
|
+
if (account.kind === "suspended") {
|
|
1672
|
+
problem(response, 403, "This account is suspended.");
|
|
1673
|
+
return;
|
|
1674
|
+
}
|
|
1675
|
+
if (account.kind === "step") {
|
|
1676
|
+
if (steps >= MAX_STEPS) {
|
|
1677
|
+
problem(response, 403, "Sign-in asked for too many steps; try again later.");
|
|
1678
|
+
return;
|
|
1679
|
+
}
|
|
1680
|
+
const handle = token();
|
|
1681
|
+
keep("step", handle, {
|
|
1682
|
+
identity,
|
|
1683
|
+
...verifiedBy !== void 0 ? { verifiedBy } : {},
|
|
1684
|
+
steps: steps + 1,
|
|
1685
|
+
flow,
|
|
1686
|
+
next
|
|
1687
|
+
});
|
|
1688
|
+
const url = new URL(account.url);
|
|
1689
|
+
url.searchParams.set("mostra_return", `${apiOrigin}/signin/return?step=${handle}`);
|
|
1690
|
+
redirect(response, url.href);
|
|
1691
|
+
return;
|
|
1692
|
+
}
|
|
1693
|
+
log.info("signin.done", { provider: identity.provider });
|
|
1694
|
+
redirect(response, `${apiOrigin}${safeNext(next)}`, { "set-cookie": [startSession(account.accountId), setCookie(flowCookie, "", 0)] });
|
|
1695
|
+
};
|
|
1696
|
+
/** The answer to a client's redirect URI, with `iss` (RFC 9207). */
|
|
1697
|
+
const toClient = (response, redirectUri, params) => {
|
|
1698
|
+
const url = new URL(redirectUri);
|
|
1699
|
+
for (const [key, value] of Object.entries(params)) if (value !== null) url.searchParams.set(key, value);
|
|
1700
|
+
url.searchParams.set("iss", apiOrigin);
|
|
1701
|
+
redirect(response, url.href);
|
|
1702
|
+
};
|
|
1703
|
+
/** Consent, or the code: a signed-in account continuing an authorization request. */
|
|
1704
|
+
const proceed = async (request, response, handle, signed) => {
|
|
1705
|
+
const pending = read("authorize", handle);
|
|
1706
|
+
if (!pending) {
|
|
1707
|
+
problem(response, 400, "This sign-in expired or was already used; start again from the app.");
|
|
1830
1708
|
return;
|
|
1831
1709
|
}
|
|
1832
|
-
const
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
}
|
|
1842
|
-
|
|
1843
|
-
const
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
const cache = String(response.headers["cache-control"] ?? "");
|
|
1854
|
-
const age = /max-age=(\d+)/.exec(cache);
|
|
1855
|
-
const noStore = /no-store|no-cache/.test(cache);
|
|
1856
|
-
resolve({
|
|
1857
|
-
status: response.statusCode ?? 0,
|
|
1858
|
-
body: Buffer.concat(chunks).toString("utf8"),
|
|
1859
|
-
maxAge: noStore ? 60 : Math.min(86400, Math.max(60, age ? Number(age[1]) : 300))
|
|
1710
|
+
const client = await clients.find(pending.clientId);
|
|
1711
|
+
if ("error" in client) {
|
|
1712
|
+
problem(response, 400, client.description);
|
|
1713
|
+
return;
|
|
1714
|
+
}
|
|
1715
|
+
const homeId = (pending.viewerSignin !== void 0 ? read("authorize", pending.viewerSignin) : void 0)?.homeId;
|
|
1716
|
+
if ((client.kind === "shell" ? homeId !== void 0 && !senderShown(signed.accountId, homeId) : !auth.consented(signed.accountId, client.id)) && request.method !== "POST") {
|
|
1717
|
+
consentPage(response, pending, client, handle, signed, homeId);
|
|
1718
|
+
return;
|
|
1719
|
+
}
|
|
1720
|
+
if (request.method === "POST") {
|
|
1721
|
+
const form = await readForm(request);
|
|
1722
|
+
if (request.headers.origin !== apiOrigin || !form || form.get("csrf") !== csrf(signed.hash, `consent ${handle}`)) {
|
|
1723
|
+
problem(response, 403, "This form must be sent from its own page.");
|
|
1724
|
+
return;
|
|
1725
|
+
}
|
|
1726
|
+
if (form.get("decision") !== "approve") {
|
|
1727
|
+
spend(handle);
|
|
1728
|
+
toClient(response, pending.redirectUri, {
|
|
1729
|
+
error: "access_denied",
|
|
1730
|
+
state: pending.state
|
|
1860
1731
|
});
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
request$2.on("close", () => clearTimeout(deadline));
|
|
1866
|
-
request$2.on("timeout", () => request$2.destroy(/* @__PURE__ */ new Error("the document took longer than 5 s")));
|
|
1867
|
-
request$2.on("error", reject);
|
|
1868
|
-
request$2.end();
|
|
1869
|
-
});
|
|
1870
|
-
const fromDocument = async (url) => {
|
|
1871
|
-
const cached = fetched.get(url.href);
|
|
1872
|
-
if (cached && cached.until > now()) return cached.client;
|
|
1873
|
-
let answer;
|
|
1874
|
-
try {
|
|
1875
|
-
answer = await fetchDocument(url);
|
|
1876
|
-
} catch (error) {
|
|
1877
|
-
log.warn("oauth.cimd_refused", {
|
|
1878
|
-
client: url.href,
|
|
1879
|
-
reason: error.message
|
|
1880
|
-
});
|
|
1881
|
-
return {
|
|
1882
|
-
error: "invalid_client",
|
|
1883
|
-
description: `The client's metadata document can't be fetched: ${error.message}.`
|
|
1884
|
-
};
|
|
1732
|
+
return;
|
|
1733
|
+
}
|
|
1734
|
+
if (client.kind === "shell" && homeId !== void 0) markSenderShown(signed.accountId, homeId);
|
|
1735
|
+
else auth.consent(signed.accountId, client.id);
|
|
1885
1736
|
}
|
|
1886
|
-
if (
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
};
|
|
1890
|
-
let document;
|
|
1891
|
-
try {
|
|
1892
|
-
document = JSON.parse(answer.body);
|
|
1893
|
-
} catch {
|
|
1894
|
-
return {
|
|
1895
|
-
error: "invalid_client",
|
|
1896
|
-
description: "The client's metadata document isn't JSON."
|
|
1897
|
-
};
|
|
1737
|
+
if (!spend(handle)) {
|
|
1738
|
+
problem(response, 400, "This sign-in was already used.");
|
|
1739
|
+
return;
|
|
1898
1740
|
}
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
|
|
1910
|
-
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
|
|
1741
|
+
clients.used(client.id);
|
|
1742
|
+
const code = auth.issueCode({
|
|
1743
|
+
clientId: client.id,
|
|
1744
|
+
redirectUri: pending.redirectUri,
|
|
1745
|
+
challenge: pending.challenge,
|
|
1746
|
+
resource: pending.resource,
|
|
1747
|
+
scope: pending.scope,
|
|
1748
|
+
accountId: signed.accountId,
|
|
1749
|
+
redirectGiven: pending.redirectGiven !== false,
|
|
1750
|
+
...pending.viewerSignin !== void 0 ? { viewerSignin: hashSecret(pending.viewerSignin) } : {}
|
|
1751
|
+
});
|
|
1752
|
+
log.info("oauth.code_issued", { client: client.id });
|
|
1753
|
+
toClient(response, pending.redirectUri, {
|
|
1754
|
+
code,
|
|
1755
|
+
state: pending.state
|
|
1756
|
+
});
|
|
1757
|
+
};
|
|
1758
|
+
const senderShown = (accountId, homeId) => directory.read((db) => db.get("SELECT 1 FROM sender_shown WHERE account_id = ? AND home_id = ?", accountId, homeId) !== void 0);
|
|
1759
|
+
const markSenderShown = (accountId, homeId) => {
|
|
1760
|
+
directory.write((db) => db.run("INSERT OR IGNORE INTO sender_shown (account_id, home_id, at) VALUES (?, ?, ?)", accountId, homeId, iso(now())));
|
|
1761
|
+
};
|
|
1762
|
+
const consentPage = (response, pending, client, handle, signed, homeId) => {
|
|
1763
|
+
const who = auth.accountName(signed.accountId).name ?? API_PAGE_WORDS.yourAccount;
|
|
1764
|
+
const redirectHost = new URL(pending.redirectUri).host;
|
|
1765
|
+
const loopback = /^(127\.0\.0\.1|\[::1\]|localhost)(:\d+)?$/.test(redirectHost);
|
|
1766
|
+
const form = {
|
|
1767
|
+
action: `/oauth/authorize/continue?authorize=${encodeURIComponent(handle)}`,
|
|
1768
|
+
csrf: csrf(signed.hash, `consent ${handle}`)
|
|
1914
1769
|
};
|
|
1915
|
-
|
|
1916
|
-
|
|
1917
|
-
|
|
1770
|
+
send(response, 200, client.kind === "shell" ? pages.answerAs(at(response), form, who, homeId !== void 0 ? options.ownerName(homeId) : void 0) : pages.allow(at(response), form, client, who, redirectHost, loopback), {}, [new URL(pending.redirectUri).origin]);
|
|
1771
|
+
};
|
|
1772
|
+
const readForm = async (request) => {
|
|
1773
|
+
if (!(request.headers["content-type"] ?? "").startsWith("application/x-www-form-urlencoded")) return;
|
|
1774
|
+
const chunks = [];
|
|
1775
|
+
let size = 0;
|
|
1776
|
+
for await (const chunk of request) {
|
|
1777
|
+
size += chunk.length;
|
|
1778
|
+
if (size > 16384) return void 0;
|
|
1779
|
+
chunks.push(chunk);
|
|
1780
|
+
}
|
|
1781
|
+
return new URLSearchParams(Buffer.concat(chunks).toString("utf8"));
|
|
1782
|
+
};
|
|
1783
|
+
/** `GET /oauth/authorize`. */
|
|
1784
|
+
const authorize = async (response, query, request) => {
|
|
1785
|
+
for (const key of new Set(query.keys())) if (query.getAll(key).length > 1) {
|
|
1786
|
+
problem(response, 400, `The request names ${key} twice.`);
|
|
1787
|
+
return;
|
|
1788
|
+
}
|
|
1789
|
+
const clientId = query.get("client_id") ?? "";
|
|
1790
|
+
const client = await clients.find(clientId);
|
|
1791
|
+
if ("error" in client) {
|
|
1792
|
+
problem(response, 400, client.description);
|
|
1793
|
+
return;
|
|
1794
|
+
}
|
|
1795
|
+
const redirectUri = query.get("redirect_uri") ?? (client.redirectUris.length === 1 ? client.redirectUris[0] : "");
|
|
1796
|
+
if (!redirectAllowed(client.redirectUris, redirectUri)) {
|
|
1797
|
+
problem(response, 400, "The redirect address isn't one this app registered.");
|
|
1798
|
+
return;
|
|
1799
|
+
}
|
|
1800
|
+
const state = query.get("state");
|
|
1801
|
+
const fail = (error, description) => toClient(response, redirectUri, {
|
|
1802
|
+
error,
|
|
1803
|
+
error_description: description,
|
|
1804
|
+
state
|
|
1918
1805
|
});
|
|
1919
|
-
if (
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
|
|
1806
|
+
if (query.get("response_type") !== "code") return fail("unsupported_response_type", "Only code.");
|
|
1807
|
+
const challenge = query.get("code_challenge") ?? "";
|
|
1808
|
+
if (query.get("code_challenge_method") !== "S256" || !/^[A-Za-z0-9_-]{43}$/.test(challenge)) return fail("invalid_request", "PKCE with S256 is required.");
|
|
1809
|
+
if (client.kind === "cli") return fail("unauthorized_client", "The CLI uses the device grant.");
|
|
1810
|
+
const scopes = (query.get("scope") ?? "mostra").split(" ").filter((part) => part !== "");
|
|
1811
|
+
if (!scopes.every((part) => part === "mostra" || part === "offline_access")) return fail("invalid_scope", "The scopes are mostra and offline_access.");
|
|
1812
|
+
const scope = ["mostra", ...scopes.includes("offline_access") ? ["offline_access"] : []].join(" ");
|
|
1813
|
+
let resource = "";
|
|
1814
|
+
let viewerSignin;
|
|
1815
|
+
if (client.kind === "shell") {
|
|
1816
|
+
viewerSignin = query.get("mostra_signin") ?? "";
|
|
1817
|
+
const started = read("authorize", viewerSignin);
|
|
1818
|
+
if (!started || started.clientId !== client.id || state !== viewerSignin) return fail("invalid_request", "This page sign-in wasn't started from its page.");
|
|
1819
|
+
resource = `${apiOrigin}/viewer`;
|
|
1820
|
+
} else {
|
|
1821
|
+
resource = canonicalResource(query.get("resource") ?? `${apiOrigin}/mcp`);
|
|
1822
|
+
if (resource !== `${apiOrigin}/mcp`) return fail("invalid_target", `The resource is ${apiOrigin}/mcp.`);
|
|
1823
|
+
}
|
|
1824
|
+
const handle = token();
|
|
1825
|
+
keep("authorize", handle, {
|
|
1826
|
+
clientId: client.id,
|
|
1827
|
+
redirectUri,
|
|
1828
|
+
state,
|
|
1829
|
+
challenge,
|
|
1830
|
+
resource,
|
|
1831
|
+
scope,
|
|
1832
|
+
...viewerSignin !== void 0 ? { viewerSignin } : {},
|
|
1833
|
+
redirectGiven: query.get("redirect_uri") !== null
|
|
1834
|
+
});
|
|
1835
|
+
const signed = sessionAccount(request);
|
|
1836
|
+
if (signed) {
|
|
1837
|
+
await proceed(request, response, handle, signed);
|
|
1838
|
+
return;
|
|
1839
|
+
}
|
|
1840
|
+
await signInPage(response, `/oauth/authorize/continue?authorize=${handle}`);
|
|
1926
1841
|
};
|
|
1927
|
-
const shellClientId = (shellOrigin) => `${shellOrigin}/_mostra/signin`;
|
|
1928
1842
|
return {
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
const
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
1949
|
-
|
|
1950
|
-
|
|
1951
|
-
const row = directory.read((db) => db.get("SELECT metadata_json FROM oauth_client WHERE id = ? AND kind = 'registered'", clientId));
|
|
1952
|
-
if (!row) return {
|
|
1953
|
-
error: "invalid_client",
|
|
1954
|
-
description: "Unknown client."
|
|
1955
|
-
};
|
|
1956
|
-
const metadata = JSON.parse(row.metadata_json);
|
|
1843
|
+
sessionAccount,
|
|
1844
|
+
csrf,
|
|
1845
|
+
signInPage,
|
|
1846
|
+
providers: async () => (await providers()).map((provider) => ({
|
|
1847
|
+
id: provider.id,
|
|
1848
|
+
label: provider.label
|
|
1849
|
+
})),
|
|
1850
|
+
startViewerSignin(signin, challenge) {
|
|
1851
|
+
const state = token();
|
|
1852
|
+
const clientId = clients.shellClientId(signin.shellOrigin);
|
|
1853
|
+
keep("authorize", state, {
|
|
1854
|
+
...signin,
|
|
1855
|
+
clientId
|
|
1856
|
+
});
|
|
1857
|
+
const url = new URL(`${apiOrigin}/oauth/authorize`);
|
|
1858
|
+
url.searchParams.set("response_type", "code");
|
|
1859
|
+
url.searchParams.set("client_id", clientId);
|
|
1860
|
+
url.searchParams.set("redirect_uri", `${signin.shellOrigin}/_mostra/signin`);
|
|
1861
|
+
url.searchParams.set("state", state);
|
|
1862
|
+
url.searchParams.set("mostra_signin", state);
|
|
1863
|
+
url.searchParams.set("code_challenge", challenge);
|
|
1864
|
+
url.searchParams.set("code_challenge_method", "S256");
|
|
1957
1865
|
return {
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
name: metadata.client_name ?? "An unnamed client",
|
|
1961
|
-
redirectUris: metadata.redirect_uris,
|
|
1962
|
-
unverified: true
|
|
1866
|
+
url: url.href,
|
|
1867
|
+
state
|
|
1963
1868
|
};
|
|
1964
1869
|
},
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
const
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
const name = typeof body.client_name === "string" ? body.client_name.trim().slice(0, 128) : void 0;
|
|
1978
|
-
const id = `mcl_${randomBytes(16).toString("hex")}`;
|
|
1979
|
-
const at = new Date(now());
|
|
1980
|
-
directory.write((db) => db.run("INSERT INTO oauth_client (id, kind, metadata_json, created_at, last_used_at) VALUES (?, 'registered', ?, ?, ?)", id, JSON.stringify({
|
|
1981
|
-
client_name: name,
|
|
1982
|
-
redirect_uris: redirects
|
|
1983
|
-
}), at.toISOString(), at.toISOString()));
|
|
1984
|
-
log.info("oauth.client_registered", { client: id });
|
|
1870
|
+
finishViewerSignin(input) {
|
|
1871
|
+
const started = read("authorize", input.state);
|
|
1872
|
+
if (!started || started.routeId !== input.routeId || started.sessionId !== input.sessionId) return { refused: "This sign-in was started for another page." };
|
|
1873
|
+
const redeemed = auth.redeemViewerCode({
|
|
1874
|
+
code: input.code,
|
|
1875
|
+
verifier: input.verifier,
|
|
1876
|
+
clientId: started.clientId,
|
|
1877
|
+
viewerSignin: hashSecret(input.state)
|
|
1878
|
+
});
|
|
1879
|
+
spend(input.state);
|
|
1880
|
+
if ("refused" in redeemed) return redeemed;
|
|
1881
|
+
const named = auth.accountName(redeemed.accountId);
|
|
1985
1882
|
return {
|
|
1986
|
-
|
|
1987
|
-
|
|
1988
|
-
...
|
|
1989
|
-
redirect_uris: redirects,
|
|
1990
|
-
token_endpoint_auth_method: "none",
|
|
1991
|
-
grant_types: ["authorization_code", "refresh_token"],
|
|
1992
|
-
response_types: ["code"]
|
|
1883
|
+
accountId: redeemed.accountId,
|
|
1884
|
+
...named.name !== void 0 ? { name: named.name } : {},
|
|
1885
|
+
...named.provider !== void 0 ? { provider: named.provider } : {}
|
|
1993
1886
|
};
|
|
1994
1887
|
},
|
|
1995
|
-
|
|
1996
|
-
|
|
1888
|
+
async handle(request, response, path) {
|
|
1889
|
+
const method = request.method ?? "GET";
|
|
1890
|
+
const url = new URL(request.url ?? "/", apiOrigin);
|
|
1891
|
+
if (method === "GET" && path === "/oauth/authorize") {
|
|
1892
|
+
await authorize(response, url.searchParams, request);
|
|
1893
|
+
return true;
|
|
1894
|
+
}
|
|
1895
|
+
if (path === "/oauth/authorize/continue" && (method === "GET" || method === "POST")) {
|
|
1896
|
+
const handle = url.searchParams.get("authorize") ?? "";
|
|
1897
|
+
const signed = sessionAccount(request);
|
|
1898
|
+
if (!signed) {
|
|
1899
|
+
await signInPage(response, `/oauth/authorize/continue?authorize=${handle}`);
|
|
1900
|
+
return true;
|
|
1901
|
+
}
|
|
1902
|
+
await proceed(request, response, handle, signed);
|
|
1903
|
+
return true;
|
|
1904
|
+
}
|
|
1905
|
+
const start = /^\/signin\/([a-z][a-z0-9-]{0,31})\/start$/.exec(path);
|
|
1906
|
+
if (method === "GET" && start) {
|
|
1907
|
+
const provider = (await providers()).find((candidate) => candidate.id === start[1]);
|
|
1908
|
+
if (!provider) {
|
|
1909
|
+
problem(response, 404, "No such sign-in.");
|
|
1910
|
+
return true;
|
|
1911
|
+
}
|
|
1912
|
+
const state = token();
|
|
1913
|
+
const verifier = token();
|
|
1914
|
+
const challenge = createHash("sha256").update(verifier).digest("base64url");
|
|
1915
|
+
const nonce = token();
|
|
1916
|
+
const flow = token();
|
|
1917
|
+
keep("provider", state, {
|
|
1918
|
+
provider: provider.id,
|
|
1919
|
+
verifier,
|
|
1920
|
+
challenge,
|
|
1921
|
+
nonce,
|
|
1922
|
+
flow: hashSecret(flow),
|
|
1923
|
+
next: safeNext(url.searchParams.get("next"))
|
|
1924
|
+
});
|
|
1925
|
+
let target;
|
|
1926
|
+
try {
|
|
1927
|
+
target = await bounded(() => provider.authorize(state, {
|
|
1928
|
+
challenge,
|
|
1929
|
+
method: "S256",
|
|
1930
|
+
verifier
|
|
1931
|
+
}, {
|
|
1932
|
+
redirectUri: `${apiOrigin}/signin/${provider.id}/callback`,
|
|
1933
|
+
nonce
|
|
1934
|
+
}), "the provider's sign-in address");
|
|
1935
|
+
const parsed = new URL(target, apiOrigin);
|
|
1936
|
+
if (parsed.protocol !== "https:" && (secure || parsed.protocol !== "http:")) throw new Error("the provider's sign-in address isn't https:");
|
|
1937
|
+
target = parsed.href;
|
|
1938
|
+
} catch (error) {
|
|
1939
|
+
log.warn("signin.provider_failed", {
|
|
1940
|
+
provider: provider.id,
|
|
1941
|
+
message: error.message
|
|
1942
|
+
});
|
|
1943
|
+
problem(response, 503, `${provider.label} can't be reached right now; try again shortly.`);
|
|
1944
|
+
return true;
|
|
1945
|
+
}
|
|
1946
|
+
redirect(response, target, { "set-cookie": setCookie(flowCookie, flow, Math.floor(PENDING_MS / 1e3)) });
|
|
1947
|
+
return true;
|
|
1948
|
+
}
|
|
1949
|
+
const name = /^\/signin\/([a-z][a-z0-9-]{0,31})\/name$/.exec(path);
|
|
1950
|
+
const callback = /^\/signin\/([a-z][a-z0-9-]{0,31})\/callback$/.exec(path);
|
|
1951
|
+
if (method === "GET" && callback || name && (method === "GET" || method === "POST")) {
|
|
1952
|
+
const id = (callback ?? name)?.[1];
|
|
1953
|
+
const provider = (await providers()).find((candidate) => candidate.id === id);
|
|
1954
|
+
if (!provider) {
|
|
1955
|
+
problem(response, 404, "No such sign-in.");
|
|
1956
|
+
return true;
|
|
1957
|
+
}
|
|
1958
|
+
if (name && method === "GET") {
|
|
1959
|
+
const state = url.searchParams.get("state") ?? "";
|
|
1960
|
+
send(response, 200, pages.developmentName(at(response), id, state));
|
|
1961
|
+
return true;
|
|
1962
|
+
}
|
|
1963
|
+
let params;
|
|
1964
|
+
if (name) {
|
|
1965
|
+
const form = await readForm(request);
|
|
1966
|
+
if (request.headers.origin !== apiOrigin || !form) {
|
|
1967
|
+
problem(response, 403, "This form must be sent from its own page.");
|
|
1968
|
+
return true;
|
|
1969
|
+
}
|
|
1970
|
+
params = Object.fromEntries(form.entries());
|
|
1971
|
+
} else {
|
|
1972
|
+
params = {};
|
|
1973
|
+
for (const key of new Set(url.searchParams.keys())) {
|
|
1974
|
+
if (url.searchParams.getAll(key).length > 1) {
|
|
1975
|
+
problem(response, 400, `The provider's answer names ${key} twice.`);
|
|
1976
|
+
return true;
|
|
1977
|
+
}
|
|
1978
|
+
params[key] = url.searchParams.get(key);
|
|
1979
|
+
}
|
|
1980
|
+
}
|
|
1981
|
+
const state = params["state"] ?? "";
|
|
1982
|
+
const pending = read("provider", state);
|
|
1983
|
+
const flow = cookies(request).get(flowCookie);
|
|
1984
|
+
if (!pending || pending.provider !== provider.id || flow === void 0 || hashSecret(flow) !== pending.flow || !spend(state)) {
|
|
1985
|
+
problem(response, 400, "This sign-in expired, was used, or was started in another browser.");
|
|
1986
|
+
return true;
|
|
1987
|
+
}
|
|
1988
|
+
let identity;
|
|
1989
|
+
try {
|
|
1990
|
+
const answered = await bounded(() => provider.callback(params, {
|
|
1991
|
+
redirectUri: `${apiOrigin}/signin/${provider.id}/callback`,
|
|
1992
|
+
nonce: pending.nonce,
|
|
1993
|
+
state,
|
|
1994
|
+
pkce: {
|
|
1995
|
+
challenge: pending.challenge,
|
|
1996
|
+
method: "S256",
|
|
1997
|
+
verifier: pending.verifier
|
|
1998
|
+
}
|
|
1999
|
+
}), "the provider's answer");
|
|
2000
|
+
const checked = SignInIdentity.safeParse({
|
|
2001
|
+
...answered,
|
|
2002
|
+
provider: provider.id
|
|
2003
|
+
});
|
|
2004
|
+
if (!checked.success) throw new Error("the provider named nobody this server can use");
|
|
2005
|
+
identity = checked.data;
|
|
2006
|
+
} catch (error) {
|
|
2007
|
+
log.warn("signin.callback_failed", {
|
|
2008
|
+
provider: provider.id,
|
|
2009
|
+
message: error.message
|
|
2010
|
+
});
|
|
2011
|
+
problem(response, 400, `${provider.label} didn't sign you in: ${error.message}`);
|
|
2012
|
+
return true;
|
|
2013
|
+
}
|
|
2014
|
+
await resolved(response, identity, verifierOf(provider), 0, pending.flow, pending.next);
|
|
2015
|
+
return true;
|
|
2016
|
+
}
|
|
2017
|
+
if (method === "GET" && path === "/signin/return") {
|
|
2018
|
+
const handle = url.searchParams.get("step") ?? "";
|
|
2019
|
+
const step = read("step", handle);
|
|
2020
|
+
const flow = cookies(request).get(flowCookie);
|
|
2021
|
+
if (!step || flow === void 0 || hashSecret(flow) !== step.flow || !spend(handle)) {
|
|
2022
|
+
problem(response, 400, "This sign-in step expired, was used, or belongs to another browser.");
|
|
2023
|
+
return true;
|
|
2024
|
+
}
|
|
2025
|
+
await resolved(response, step.identity, step.verifiedBy, step.steps, step.flow, step.next);
|
|
2026
|
+
return true;
|
|
2027
|
+
}
|
|
2028
|
+
return false;
|
|
1997
2029
|
}
|
|
1998
|
-
};
|
|
1999
|
-
}
|
|
2000
|
-
//#endregion
|
|
2001
|
-
//#region src/server/authorize.ts
|
|
2002
|
-
/**
|
|
2003
|
-
* The authorization server's pages on the API origin (INTERFACES §18.5, D165 items 8, 10):
|
|
2004
|
-
*
|
|
2005
|
-
* - `GET /oauth/authorize`: the authorization code flow with PKCE (S256) for MCP clients (Client
|
|
2006
|
-
* ID Metadata Documents, registered clients) and for each hosted shell's viewer sign-in. The
|
|
2007
|
-
* client and its redirect URI are checked before anything is redirected anywhere; an `iss`
|
|
2008
|
-
* parameter goes with every answer (RFC 9207).
|
|
2009
|
-
* - Sign-in through an identity provider (`/signin/<id>/start`, its `callback`), into a browser
|
|
2010
|
-
* session on the API origin only, never the user-content domain; the operator's first sign-in
|
|
2011
|
-
* steps (`/signin/return`).
|
|
2012
|
-
* - The server's own consent page (`/oauth/consent`), for every client an account hasn't
|
|
2013
|
-
* approved, never skipped because a provider skipped its own; for a page's sign-in it names
|
|
2014
|
-
* the page's sender instead, once per account and home.
|
|
2015
|
-
*
|
|
2016
|
-
* Every in-progress record (an authorization request, a provider sign-in, a first sign-in step)
|
|
2017
|
-
* is kept only as the SHA-256 of its handle, lives minutes, is used once, and is bound to the
|
|
2018
|
-
* browser that started it by a cookie of the API origin.
|
|
2019
|
-
*/
|
|
2020
|
-
/** How long an authorization request, a provider sign-in or a step waits. */
|
|
2021
|
-
const PENDING_MS = 9e5;
|
|
2022
|
-
/** How long a browser stays signed in to the API origin. */
|
|
2023
|
-
const SESSION_MS = 6048e5;
|
|
2024
|
-
/** At most this many first sign-in steps per sign-in (D167). */
|
|
2025
|
-
const MAX_STEPS = 3;
|
|
2026
|
-
/**
|
|
2027
|
-
* How long an identity provider's own calls may take (its authorization address, the code's
|
|
2028
|
-
* exchange): inside the 10 s every endpoint of the authorization server answers in (D165 item 10),
|
|
2029
|
-
* whether the provider is built in or the operator's.
|
|
2030
|
-
*/
|
|
2031
|
-
const PROVIDER_MS = 8e3;
|
|
2032
|
-
/** A provider's call, or a refusal once it took longer than {@link PROVIDER_MS}. */
|
|
2033
|
-
async function bounded(call, what) {
|
|
2034
|
-
let timer;
|
|
2035
|
-
try {
|
|
2036
|
-
return await Promise.race([Promise.resolve().then(call), new Promise((_, reject) => {
|
|
2037
|
-
timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`${what} took too long`)), PROVIDER_MS);
|
|
2038
|
-
})]);
|
|
2039
|
-
} finally {
|
|
2040
|
-
clearTimeout(timer);
|
|
2041
|
-
}
|
|
2030
|
+
};
|
|
2042
2031
|
}
|
|
2043
|
-
|
|
2032
|
+
//#endregion
|
|
2033
|
+
//#region src/server/api.ts
|
|
2034
|
+
/**
|
|
2035
|
+
* The remote server's API origin (INTERFACES §18.2, §18.5): the authorization server's device
|
|
2036
|
+
* grant (`/oauth/device`, `/oauth/token`, `/oauth/revoke`, its metadata and the device page), the
|
|
2037
|
+
* network binding (`/host`, JSON-RPC over WebSocket with a bearer token) and version files
|
|
2038
|
+
* (`PUT /files/<sha256>`). Never on a user-content domain (D165 item 7).
|
|
2039
|
+
*/
|
|
2040
|
+
/** How often an open binding's grant is checked again: a revocation closes it within 60 s. */
|
|
2041
|
+
const GRANT_RECHECK_MS = 3e4;
|
|
2042
|
+
/** How often the operator is asked again whether an account is suspended (`accounts.status`). */
|
|
2043
|
+
const STATUS_RECHECK_MS = 3e4;
|
|
2044
|
+
/** Dynamic Client Registrations an address may make a minute (D167). */
|
|
2045
|
+
const REGISTRATIONS_PER_MINUTE = 10;
|
|
2046
|
+
/** The largest version file accepted (per file; an operator's storage limit is WP-30's). */
|
|
2047
|
+
const MAX_FILE_BYTES = 268435456;
|
|
2048
|
+
const BASE_HEADERS = {
|
|
2044
2049
|
"cache-control": "no-store",
|
|
2045
2050
|
"cross-origin-resource-policy": "same-origin",
|
|
2046
|
-
"
|
|
2047
|
-
"x-
|
|
2051
|
+
"referrer-policy": "no-referrer",
|
|
2052
|
+
"x-content-type-options": "nosniff"
|
|
2048
2053
|
};
|
|
2049
|
-
function
|
|
2050
|
-
|
|
2054
|
+
function send(response, status, body, headers = {}) {
|
|
2055
|
+
const text = JSON.stringify(body);
|
|
2056
|
+
response.writeHead(status, {
|
|
2057
|
+
...BASE_HEADERS,
|
|
2058
|
+
"content-type": "application/json; charset=utf-8",
|
|
2059
|
+
"content-length": String(Buffer.byteLength(text)),
|
|
2060
|
+
...headers
|
|
2061
|
+
});
|
|
2062
|
+
response.end(text);
|
|
2051
2063
|
}
|
|
2052
|
-
function
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2064
|
+
async function readBody(request, limit) {
|
|
2065
|
+
const chunks = [];
|
|
2066
|
+
let size = 0;
|
|
2067
|
+
for await (const chunk of request) {
|
|
2068
|
+
size += chunk.length;
|
|
2069
|
+
if (size > limit) return void 0;
|
|
2070
|
+
chunks.push(chunk);
|
|
2071
|
+
}
|
|
2072
|
+
return Buffer.concat(chunks);
|
|
2058
2073
|
}
|
|
2059
|
-
/**
|
|
2060
|
-
function
|
|
2061
|
-
const
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
if (!found.has(name)) found.set(name, part.slice(at + 1).trim());
|
|
2075
|
-
}
|
|
2076
|
-
return found;
|
|
2077
|
-
};
|
|
2078
|
-
const setCookie = (name, value, maxAgeS) => `${name}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAgeS}${secure ? "; Secure" : ""}`;
|
|
2079
|
-
const send = (response, status, html, extra = {}, formTargets = []) => {
|
|
2074
|
+
/** The development identity provider, when the configuration names one (§18.5, WP-29). */
|
|
2075
|
+
function developmentProvider$1(config) {
|
|
2076
|
+
const provider = config.identityProviders?.find((candidate) => candidate.kind === "development");
|
|
2077
|
+
return provider ? {
|
|
2078
|
+
id: provider.id,
|
|
2079
|
+
label: provider.label ?? "Development sign-in"
|
|
2080
|
+
} : void 0;
|
|
2081
|
+
}
|
|
2082
|
+
/** Creates the API origin. */
|
|
2083
|
+
function createApi(options) {
|
|
2084
|
+
const { config, auth, log } = options;
|
|
2085
|
+
const apiOrigin = config.apiOrigin;
|
|
2086
|
+
const pages = createApiPages(options.server, options.server.name);
|
|
2087
|
+
/** Sends one of the API origin's pages: themed, no script, its forms posting here only. */
|
|
2088
|
+
const page = (response, status, text) => {
|
|
2080
2089
|
response.writeHead(status, {
|
|
2081
|
-
...
|
|
2090
|
+
...BASE_HEADERS,
|
|
2082
2091
|
"content-type": "text/html; charset=utf-8",
|
|
2083
|
-
"content-security-policy":
|
|
2084
|
-
"
|
|
2085
|
-
|
|
2086
|
-
});
|
|
2087
|
-
response.end(html);
|
|
2088
|
-
};
|
|
2089
|
-
const redirect = (response, location, extra = {}) => {
|
|
2090
|
-
response.writeHead(303, {
|
|
2091
|
-
...BASE,
|
|
2092
|
-
location,
|
|
2093
|
-
"referrer-policy": "no-referrer",
|
|
2094
|
-
...extra
|
|
2092
|
+
"content-security-policy": themePageCsp(options.server.pages, "'none'", "'self'"),
|
|
2093
|
+
"x-frame-options": "DENY",
|
|
2094
|
+
"referrer-policy": "same-origin"
|
|
2095
2095
|
});
|
|
2096
|
-
response.end();
|
|
2096
|
+
response.end(text);
|
|
2097
2097
|
};
|
|
2098
|
-
const
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2098
|
+
const devicePage = (response, options) => options.done ? pages.deviceDone(pageRequest(response), options.message ?? "") : pages.deviceForm(pageRequest(response), {
|
|
2099
|
+
code: options.code,
|
|
2100
|
+
message: options.message,
|
|
2101
|
+
development: options.provider
|
|
2102
2102
|
});
|
|
2103
|
-
const
|
|
2104
|
-
|
|
2105
|
-
|
|
2103
|
+
const sockets = new WebSocketServer({
|
|
2104
|
+
noServer: true,
|
|
2105
|
+
maxPayload: MAX_FRAME_BYTES,
|
|
2106
|
+
perMessageDeflate: false,
|
|
2107
|
+
handleProtocols: (protocols) => protocols.has("mostra.host") ? BINDING_SUBPROTOCOL : false
|
|
2106
2108
|
});
|
|
2107
|
-
const
|
|
2108
|
-
const
|
|
2109
|
-
const value = cookies(request).get(sessionCookie);
|
|
2110
|
-
if (value === void 0 || !/^[A-Za-z0-9_-]{43}$/.test(value)) return void 0;
|
|
2111
|
-
const hash = hashSecret(value);
|
|
2112
|
-
const row = directory.read((db) => db.get(`SELECT s.account_id, s.expires_at, a.status FROM browser_session s
|
|
2113
|
-
JOIN account a ON a.id = s.account_id WHERE s.hash = ?`, hash));
|
|
2114
|
-
if (!row || Date.parse(row.expires_at) <= now() || row.status !== "active") return void 0;
|
|
2115
|
-
return {
|
|
2116
|
-
accountId: row.account_id,
|
|
2117
|
-
hash
|
|
2118
|
-
};
|
|
2119
|
-
};
|
|
2120
|
-
const startSession = (accountId) => {
|
|
2121
|
-
const value = token();
|
|
2122
|
-
directory.write((db) => db.run("INSERT INTO browser_session (hash, account_id, created_at, expires_at) VALUES (?, ?, ?, ?)", hashSecret(value), accountId, iso(now()), iso(now() + SESSION_MS)));
|
|
2123
|
-
return setCookie(sessionCookie, value, Math.floor(SESSION_MS / 1e3));
|
|
2124
|
-
};
|
|
2125
|
-
const csrf = (sessionHash, purpose) => createHash("sha256").update(`mostra csrf ${sessionHash} ${purpose}`).digest("base64url");
|
|
2109
|
+
const bindings = /* @__PURE__ */ new Set();
|
|
2110
|
+
const bindingHomes = /* @__PURE__ */ new Map();
|
|
2126
2111
|
/**
|
|
2127
|
-
*
|
|
2128
|
-
*
|
|
2112
|
+
* Whether the device page offers the development provider's form (D166 item 4): only while it is
|
|
2113
|
+
* the one provider a sign-in may use now, none other configured and none the operator supplies.
|
|
2114
|
+
* The page's GET and its POST judge by this one rule.
|
|
2129
2115
|
*/
|
|
2130
|
-
const
|
|
2131
|
-
const
|
|
2132
|
-
|
|
2133
|
-
|
|
2134
|
-
return
|
|
2135
|
-
};
|
|
2136
|
-
/** The providers now: configured ones, then the operator's (asked each time, D167). */
|
|
2137
|
-
const providers = async () => {
|
|
2138
|
-
const supplied = await operator.providers();
|
|
2139
|
-
const ids = new Set(options.providers.map((provider) => provider.id));
|
|
2140
|
-
return [...options.providers, ...supplied.filter((provider) => !ids.has(provider.id))];
|
|
2141
|
-
};
|
|
2142
|
-
/** The page listing the providers; each starts a sign-in that returns to `next`. */
|
|
2143
|
-
const signInPage = async (response, next, message) => {
|
|
2144
|
-
const links = (await providers()).map((provider) => `<p><a class="button" href="/signin/${encodeURIComponent(provider.id)}/start?next=${encodeURIComponent(next)}">Continue with ${escapeHtml(provider.label)}</a></p>`).join("");
|
|
2145
|
-
send(response, 200, shell("Sign in to Mostra", `${message ? `<p role="alert">${escapeHtml(message)}</p>` : ""}${links || "<p>This server has no identity provider configured, so nobody can sign in yet.</p>"}`));
|
|
2146
|
-
};
|
|
2147
|
-
/** Where a finished sign-in continues: an address of the API origin only. */
|
|
2148
|
-
const safeNext = (next) => next?.startsWith("/") && !next.startsWith("//") ? next : "/";
|
|
2149
|
-
/** A resolved identity: a session and on to `next`, a step, or why not. */
|
|
2150
|
-
const resolved = async (response, identity, verifiedBy, steps, flow, next) => {
|
|
2151
|
-
const account = await auth.resolveAccount(identity, steps, verifiedBy);
|
|
2152
|
-
if (account.kind === "unavailable") {
|
|
2153
|
-
problem(response, 503, "Sign-in is unavailable for a moment; try again shortly.");
|
|
2154
|
-
return;
|
|
2155
|
-
}
|
|
2156
|
-
if (account.kind === "refused") {
|
|
2157
|
-
problem(response, 403, account.message);
|
|
2158
|
-
return;
|
|
2159
|
-
}
|
|
2160
|
-
if (account.kind === "suspended") {
|
|
2161
|
-
problem(response, 403, "This account is suspended.");
|
|
2162
|
-
return;
|
|
2163
|
-
}
|
|
2164
|
-
if (account.kind === "step") {
|
|
2165
|
-
if (steps >= MAX_STEPS) {
|
|
2166
|
-
problem(response, 403, "Sign-in asked for too many steps; try again later.");
|
|
2167
|
-
return;
|
|
2168
|
-
}
|
|
2169
|
-
const handle = token();
|
|
2170
|
-
keep("step", handle, {
|
|
2171
|
-
identity,
|
|
2172
|
-
...verifiedBy !== void 0 ? { verifiedBy } : {},
|
|
2173
|
-
steps: steps + 1,
|
|
2174
|
-
flow,
|
|
2175
|
-
next
|
|
2176
|
-
});
|
|
2177
|
-
const url = new URL(account.url);
|
|
2178
|
-
url.searchParams.set("mostra_return", `${apiOrigin}/signin/return?step=${handle}`);
|
|
2179
|
-
redirect(response, url.href);
|
|
2180
|
-
return;
|
|
2181
|
-
}
|
|
2182
|
-
log.info("signin.done", { provider: identity.provider });
|
|
2183
|
-
redirect(response, `${apiOrigin}${safeNext(next)}`, { "set-cookie": [startSession(account.accountId), setCookie(flowCookie, "", 0)] });
|
|
2184
|
-
};
|
|
2185
|
-
/** The answer to a client's redirect URI, with `iss` (RFC 9207). */
|
|
2186
|
-
const toClient = (response, redirectUri, params) => {
|
|
2187
|
-
const url = new URL(redirectUri);
|
|
2188
|
-
for (const [key, value] of Object.entries(params)) if (value !== null) url.searchParams.set(key, value);
|
|
2189
|
-
url.searchParams.set("iss", apiOrigin);
|
|
2190
|
-
redirect(response, url.href);
|
|
2116
|
+
const devFormOffered = async () => {
|
|
2117
|
+
const development = developmentProvider$1(config);
|
|
2118
|
+
if (development === void 0) return false;
|
|
2119
|
+
const offered = await options.authorize.providers();
|
|
2120
|
+
return offered.length === 1 && offered[0]?.id === development.id;
|
|
2191
2121
|
};
|
|
2192
|
-
/**
|
|
2193
|
-
|
|
2194
|
-
|
|
2195
|
-
|
|
2196
|
-
|
|
2197
|
-
|
|
2198
|
-
|
|
2199
|
-
|
|
2200
|
-
if (
|
|
2201
|
-
|
|
2202
|
-
|
|
2203
|
-
|
|
2204
|
-
|
|
2205
|
-
|
|
2206
|
-
|
|
2207
|
-
|
|
2208
|
-
|
|
2209
|
-
|
|
2210
|
-
|
|
2211
|
-
if (request.headers.origin !== apiOrigin || !form || form.get("csrf") !== csrf(signed.hash, `consent ${handle}`)) {
|
|
2212
|
-
problem(response, 403, "This form must be sent from its own page.");
|
|
2213
|
-
return;
|
|
2214
|
-
}
|
|
2215
|
-
if (form.get("decision") !== "approve") {
|
|
2216
|
-
spend(handle);
|
|
2217
|
-
toClient(response, pending.redirectUri, {
|
|
2218
|
-
error: "access_denied",
|
|
2219
|
-
state: pending.state
|
|
2220
|
-
});
|
|
2221
|
-
return;
|
|
2222
|
-
}
|
|
2223
|
-
if (client.kind === "shell" && homeId !== void 0) markSenderShown(signed.accountId, homeId);
|
|
2224
|
-
else auth.consent(signed.accountId, client.id);
|
|
2225
|
-
}
|
|
2226
|
-
if (!spend(handle)) {
|
|
2227
|
-
problem(response, 400, "This sign-in was already used.");
|
|
2228
|
-
return;
|
|
2229
|
-
}
|
|
2230
|
-
clients.used(client.id);
|
|
2231
|
-
const code = auth.issueCode({
|
|
2232
|
-
clientId: client.id,
|
|
2233
|
-
redirectUri: pending.redirectUri,
|
|
2234
|
-
challenge: pending.challenge,
|
|
2235
|
-
resource: pending.resource,
|
|
2236
|
-
scope: pending.scope,
|
|
2237
|
-
accountId: signed.accountId,
|
|
2238
|
-
redirectGiven: pending.redirectGiven !== false,
|
|
2239
|
-
...pending.viewerSignin !== void 0 ? { viewerSignin: hashSecret(pending.viewerSignin) } : {}
|
|
2240
|
-
});
|
|
2241
|
-
log.info("oauth.code_issued", { client: client.id });
|
|
2242
|
-
toClient(response, pending.redirectUri, {
|
|
2243
|
-
code,
|
|
2244
|
-
state: pending.state
|
|
2245
|
-
});
|
|
2122
|
+
/**
|
|
2123
|
+
* The operator's word on accounts (`accounts.status`, §18.6), asked at most every 30 s per
|
|
2124
|
+
* account and written into the directory, so a suspension reaches every grant: its refreshes, its
|
|
2125
|
+
* bindings, its MCP calls (Fable review of WP-30, 6). An operator that doesn't answer leaves the
|
|
2126
|
+
* last word standing.
|
|
2127
|
+
*/
|
|
2128
|
+
const statusAsked = /* @__PURE__ */ new Map();
|
|
2129
|
+
const accountStanding = async (accountId) => {
|
|
2130
|
+
if (options.operator?.has.status === true) {
|
|
2131
|
+
const last = statusAsked.get(accountId);
|
|
2132
|
+
const every = Math.min(STATUS_RECHECK_MS, options.recheckMs ?? STATUS_RECHECK_MS);
|
|
2133
|
+
if (last === void 0 || Date.now() - last >= every) {
|
|
2134
|
+
statusAsked.set(accountId, Date.now());
|
|
2135
|
+
if (statusAsked.size > 1e4) statusAsked.delete(statusAsked.keys().next().value);
|
|
2136
|
+
const said = await options.operator.status(accountId);
|
|
2137
|
+
if (said !== void 0) auth.setAccountStatus(accountId, said);
|
|
2138
|
+
}
|
|
2139
|
+
}
|
|
2140
|
+
return auth.accountStatus(accountId);
|
|
2246
2141
|
};
|
|
2247
|
-
|
|
2248
|
-
|
|
2249
|
-
|
|
2142
|
+
/**
|
|
2143
|
+
* Whether an authenticated caller may act now: its home not suspended by the operator, its
|
|
2144
|
+
* account not suspended (D165 item 9). One place for `/host`, `/files`, `/mcp` and `/link`
|
|
2145
|
+
* (Fable review of WP-30, 1).
|
|
2146
|
+
*/
|
|
2147
|
+
const standing = async (who) => {
|
|
2148
|
+
if (options.suspended?.(who.homeId) || await accountStanding(who.accountId) === "suspended") return createDiagnostic("MOSTRA_REMOTE_HOME_SUSPENDED", { message: "This account's pages are suspended by the server's operator." });
|
|
2250
2149
|
};
|
|
2251
|
-
|
|
2252
|
-
|
|
2253
|
-
|
|
2254
|
-
|
|
2255
|
-
|
|
2256
|
-
|
|
2257
|
-
|
|
2258
|
-
|
|
2259
|
-
|
|
2260
|
-
|
|
2150
|
+
/**
|
|
2151
|
+
* The account a bearer token names for one resource (`host`, `files` or `mcp`): a token this
|
|
2152
|
+
* server issued for exactly that audience (RFC 8707; a token for `/mcp` opens no binding), or a
|
|
2153
|
+
* credential the operator issued (`accounts.authenticate`, §18.6); or why it may not act now.
|
|
2154
|
+
*/
|
|
2155
|
+
const bearer = async (request, resource) => {
|
|
2156
|
+
const header = request.headers.authorization ?? "";
|
|
2157
|
+
const match = /^bearer\s+(\S+)$/i.exec(header);
|
|
2158
|
+
if (!match) return void 0;
|
|
2159
|
+
const token = match[1];
|
|
2160
|
+
const audience = `${apiOrigin}/${resource === "files" ? "host" : resource}`;
|
|
2161
|
+
const issued = auth.authenticate(token);
|
|
2162
|
+
let who;
|
|
2163
|
+
if (issued) {
|
|
2164
|
+
if (issued.resource !== audience) return void 0;
|
|
2165
|
+
who = issued;
|
|
2166
|
+
} else {
|
|
2167
|
+
if (!options.operator?.has.authenticate) return void 0;
|
|
2168
|
+
const credential = await options.operator.authenticate(token, resource);
|
|
2169
|
+
if (!credential?.scope.includes("mostra")) return void 0;
|
|
2170
|
+
who = auth.credentialSession({
|
|
2171
|
+
account: credential.account,
|
|
2172
|
+
subject: credential.subject ?? "default",
|
|
2173
|
+
resource: audience,
|
|
2174
|
+
link: resource === "host"
|
|
2175
|
+
});
|
|
2176
|
+
}
|
|
2177
|
+
const refused = await standing(who);
|
|
2178
|
+
return refused ? { refused } : who;
|
|
2261
2179
|
};
|
|
2262
|
-
const
|
|
2263
|
-
|
|
2264
|
-
|
|
2265
|
-
|
|
2266
|
-
|
|
2267
|
-
|
|
2268
|
-
|
|
2269
|
-
|
|
2180
|
+
const unauthorized = (response, message) => send(response, 401, {
|
|
2181
|
+
code: "MOSTRA_REMOTE_LOGIN_FAILED",
|
|
2182
|
+
message
|
|
2183
|
+
}, { "www-authenticate": `Bearer resource_metadata="${apiOrigin}/.well-known/oauth-protected-resource/host"` });
|
|
2184
|
+
/**
|
|
2185
|
+
* RFC 8414 metadata (INTERFACES §18.5): Client ID Metadata Documents with `none` among the token
|
|
2186
|
+
* endpoint's methods, which Claude needs before it uses one, Dynamic Client Registration as the
|
|
2187
|
+
* fallback, PKCE S256, `iss` in responses, and `offline_access` for rotating refresh tokens.
|
|
2188
|
+
*/
|
|
2189
|
+
const metadata = () => ({
|
|
2190
|
+
issuer: apiOrigin,
|
|
2191
|
+
authorization_endpoint: `${apiOrigin}/oauth/authorize`,
|
|
2192
|
+
token_endpoint: `${apiOrigin}/oauth/token`,
|
|
2193
|
+
registration_endpoint: `${apiOrigin}/oauth/register`,
|
|
2194
|
+
device_authorization_endpoint: `${apiOrigin}/oauth/device`,
|
|
2195
|
+
revocation_endpoint: `${apiOrigin}/oauth/revoke`,
|
|
2196
|
+
response_types_supported: ["code"],
|
|
2197
|
+
response_modes_supported: ["query"],
|
|
2198
|
+
grant_types_supported: [
|
|
2199
|
+
"authorization_code",
|
|
2200
|
+
"refresh_token",
|
|
2201
|
+
"urn:ietf:params:oauth:grant-type:device_code"
|
|
2202
|
+
],
|
|
2203
|
+
token_endpoint_auth_methods_supported: ["none"],
|
|
2204
|
+
revocation_endpoint_auth_methods_supported: ["none"],
|
|
2205
|
+
code_challenge_methods_supported: ["S256"],
|
|
2206
|
+
scopes_supported: ["mostra", "offline_access"],
|
|
2207
|
+
client_id_metadata_document_supported: true,
|
|
2208
|
+
authorization_response_iss_parameter_supported: true
|
|
2209
|
+
});
|
|
2210
|
+
const sessionDevicePage = (response, code, signed) => pages.deviceForm(pageRequest(response), {
|
|
2211
|
+
code,
|
|
2212
|
+
signedIn: {
|
|
2213
|
+
name: auth.accountName(signed.accountId).name ?? API_PAGE_WORDS.yourAccount,
|
|
2214
|
+
csrf: options.authorize.csrf(signed.hash, "device")
|
|
2270
2215
|
}
|
|
2271
|
-
|
|
2216
|
+
});
|
|
2217
|
+
const form = async (request) => {
|
|
2218
|
+
if (!(request.headers["content-type"] ?? "").startsWith("application/x-www-form-urlencoded")) return void 0;
|
|
2219
|
+
const body = await readBody(request, 65536);
|
|
2220
|
+
return body === void 0 ? void 0 : new URLSearchParams(body.toString("utf8"));
|
|
2272
2221
|
};
|
|
2273
|
-
|
|
2274
|
-
|
|
2275
|
-
|
|
2276
|
-
|
|
2222
|
+
const upload = async (request, response, sha) => {
|
|
2223
|
+
const who = await bearer(request, "files");
|
|
2224
|
+
if (!who) {
|
|
2225
|
+
unauthorized(response, "Version files need the binding's access token.");
|
|
2277
2226
|
return;
|
|
2278
2227
|
}
|
|
2279
|
-
|
|
2280
|
-
|
|
2281
|
-
if ("error" in client) {
|
|
2282
|
-
problem(response, 400, client.description);
|
|
2228
|
+
if ("refused" in who) {
|
|
2229
|
+
send(response, 403, who.refused);
|
|
2283
2230
|
return;
|
|
2284
2231
|
}
|
|
2285
|
-
const
|
|
2286
|
-
|
|
2287
|
-
|
|
2232
|
+
const home = await options.home(who.homeId);
|
|
2233
|
+
options.touch(who.homeId);
|
|
2234
|
+
const declared = home.wanted(sha);
|
|
2235
|
+
if (declared === void 0) {
|
|
2236
|
+
send(response, 409, {
|
|
2237
|
+
code: "MOSTRA_HOME_INTEGRITY",
|
|
2238
|
+
message: "No pending push of this home names that file as missing."
|
|
2239
|
+
});
|
|
2288
2240
|
return;
|
|
2289
2241
|
}
|
|
2290
|
-
|
|
2291
|
-
const
|
|
2292
|
-
|
|
2293
|
-
|
|
2294
|
-
|
|
2295
|
-
|
|
2296
|
-
|
|
2297
|
-
|
|
2298
|
-
|
|
2299
|
-
|
|
2300
|
-
|
|
2301
|
-
|
|
2302
|
-
|
|
2303
|
-
let resource = "";
|
|
2304
|
-
let viewerSignin;
|
|
2305
|
-
if (client.kind === "shell") {
|
|
2306
|
-
viewerSignin = query.get("mostra_signin") ?? "";
|
|
2307
|
-
const started = read("authorize", viewerSignin);
|
|
2308
|
-
if (!started || started.clientId !== client.id || state !== viewerSignin) return fail("invalid_request", "This page sign-in wasn't started from its page.");
|
|
2309
|
-
resource = `${apiOrigin}/viewer`;
|
|
2310
|
-
} else {
|
|
2311
|
-
resource = canonicalResource(query.get("resource") ?? `${apiOrigin}/mcp`);
|
|
2312
|
-
if (resource !== `${apiOrigin}/mcp`) return fail("invalid_target", `The resource is ${apiOrigin}/mcp.`);
|
|
2242
|
+
/** Refuses the upload and closes its connection once the answer is out: the rest isn't read. */
|
|
2243
|
+
const refuseUpload = (status, message) => {
|
|
2244
|
+
response.once("finish", () => request.destroy());
|
|
2245
|
+
send(response, status, {
|
|
2246
|
+
code: "MOSTRA_HOME_INTEGRITY",
|
|
2247
|
+
message
|
|
2248
|
+
}, { connection: "close" });
|
|
2249
|
+
};
|
|
2250
|
+
const sizeMessage = "The file's bytes aren't the size its push gave them.";
|
|
2251
|
+
const announced = request.headers["content-length"];
|
|
2252
|
+
if (announced !== void 0 && Number(announced) !== declared) {
|
|
2253
|
+
refuseUpload(declared > MAX_FILE_BYTES ? 413 : 400, sizeMessage);
|
|
2254
|
+
return;
|
|
2313
2255
|
}
|
|
2314
|
-
const
|
|
2315
|
-
|
|
2316
|
-
|
|
2317
|
-
|
|
2318
|
-
|
|
2319
|
-
|
|
2320
|
-
|
|
2321
|
-
|
|
2322
|
-
|
|
2323
|
-
|
|
2324
|
-
|
|
2325
|
-
|
|
2326
|
-
|
|
2327
|
-
|
|
2256
|
+
const target = join(options.filesDir, sha);
|
|
2257
|
+
const scratch = join(options.filesDir, `.upload-${randomBytes(8).toString("hex")}`);
|
|
2258
|
+
const hash = createHash("sha256");
|
|
2259
|
+
let size = 0;
|
|
2260
|
+
let tooLarge = false;
|
|
2261
|
+
await new Promise((resolve, reject) => {
|
|
2262
|
+
const out = createWriteStream(scratch, { mode: 384 });
|
|
2263
|
+
const onData = (chunk) => {
|
|
2264
|
+
size += chunk.length;
|
|
2265
|
+
if (size > MAX_FILE_BYTES || size > declared) {
|
|
2266
|
+
tooLarge = true;
|
|
2267
|
+
request.off("data", onData);
|
|
2268
|
+
request.pause();
|
|
2269
|
+
out.end(() => resolve());
|
|
2270
|
+
return;
|
|
2271
|
+
}
|
|
2272
|
+
hash.update(chunk);
|
|
2273
|
+
out.write(chunk);
|
|
2274
|
+
};
|
|
2275
|
+
request.on("data", onData);
|
|
2276
|
+
request.on("end", () => {
|
|
2277
|
+
if (!tooLarge) out.end(() => resolve());
|
|
2278
|
+
});
|
|
2279
|
+
request.on("error", reject);
|
|
2280
|
+
request.on("close", () => out.end(() => resolve()));
|
|
2281
|
+
}).catch(() => void 0);
|
|
2282
|
+
const shortOrLong = !tooLarge && size !== declared;
|
|
2283
|
+
if (tooLarge || shortOrLong || hash.digest("hex") !== sha) {
|
|
2284
|
+
await rm(scratch, { force: true });
|
|
2285
|
+
refuseUpload(tooLarge && size > MAX_FILE_BYTES ? 413 : 400, tooLarge || shortOrLong ? sizeMessage : "The bytes don't hash to the file's name.");
|
|
2328
2286
|
return;
|
|
2329
2287
|
}
|
|
2330
|
-
await
|
|
2288
|
+
if (existsSync(target)) await rm(scratch, { force: true });
|
|
2289
|
+
else renameSync(scratch, target);
|
|
2290
|
+
home.uploaded(sha, size);
|
|
2291
|
+
options.stored?.(who.homeId, size);
|
|
2292
|
+
send(response, 201, {
|
|
2293
|
+
sha256: sha,
|
|
2294
|
+
size
|
|
2295
|
+
});
|
|
2331
2296
|
};
|
|
2332
2297
|
return {
|
|
2333
|
-
|
|
2334
|
-
csrf,
|
|
2335
|
-
signInPage,
|
|
2336
|
-
providers: async () => (await providers()).map((provider) => ({
|
|
2337
|
-
id: provider.id,
|
|
2338
|
-
label: provider.label
|
|
2339
|
-
})),
|
|
2340
|
-
startViewerSignin(signin, challenge) {
|
|
2341
|
-
const state = token();
|
|
2342
|
-
const clientId = clients.shellClientId(signin.shellOrigin);
|
|
2343
|
-
keep("authorize", state, {
|
|
2344
|
-
...signin,
|
|
2345
|
-
clientId
|
|
2346
|
-
});
|
|
2347
|
-
const url = new URL(`${apiOrigin}/oauth/authorize`);
|
|
2348
|
-
url.searchParams.set("response_type", "code");
|
|
2349
|
-
url.searchParams.set("client_id", clientId);
|
|
2350
|
-
url.searchParams.set("redirect_uri", `${signin.shellOrigin}/_mostra/signin`);
|
|
2351
|
-
url.searchParams.set("state", state);
|
|
2352
|
-
url.searchParams.set("mostra_signin", state);
|
|
2353
|
-
url.searchParams.set("code_challenge", challenge);
|
|
2354
|
-
url.searchParams.set("code_challenge_method", "S256");
|
|
2355
|
-
return {
|
|
2356
|
-
url: url.href,
|
|
2357
|
-
state
|
|
2358
|
-
};
|
|
2359
|
-
},
|
|
2360
|
-
finishViewerSignin(input) {
|
|
2361
|
-
const started = read("authorize", input.state);
|
|
2362
|
-
if (!started || started.routeId !== input.routeId || started.sessionId !== input.sessionId) return { refused: "This sign-in was started for another page." };
|
|
2363
|
-
const redeemed = auth.redeemViewerCode({
|
|
2364
|
-
code: input.code,
|
|
2365
|
-
verifier: input.verifier,
|
|
2366
|
-
clientId: started.clientId,
|
|
2367
|
-
viewerSignin: hashSecret(input.state)
|
|
2368
|
-
});
|
|
2369
|
-
spend(input.state);
|
|
2370
|
-
if ("refused" in redeemed) return redeemed;
|
|
2371
|
-
const named = auth.accountName(redeemed.accountId);
|
|
2372
|
-
return {
|
|
2373
|
-
accountId: redeemed.accountId,
|
|
2374
|
-
...named.name !== void 0 ? { name: named.name } : {},
|
|
2375
|
-
...named.provider !== void 0 ? { provider: named.provider } : {}
|
|
2376
|
-
};
|
|
2377
|
-
},
|
|
2378
|
-
async handle(request, response, path) {
|
|
2298
|
+
async request(request, response, path) {
|
|
2379
2299
|
const method = request.method ?? "GET";
|
|
2380
|
-
|
|
2381
|
-
|
|
2382
|
-
|
|
2383
|
-
return true;
|
|
2300
|
+
if (method === "GET" && path === "/.well-known/oauth-authorization-server") {
|
|
2301
|
+
send(response, 200, metadata());
|
|
2302
|
+
return;
|
|
2384
2303
|
}
|
|
2385
|
-
if (
|
|
2386
|
-
|
|
2387
|
-
|
|
2388
|
-
|
|
2389
|
-
|
|
2390
|
-
|
|
2391
|
-
|
|
2392
|
-
|
|
2393
|
-
|
|
2304
|
+
if (await options.authorize.handle(request, response, path)) return;
|
|
2305
|
+
if (method === "GET" && path === "/.well-known/oauth-protected-resource/mcp") {
|
|
2306
|
+
send(response, 200, {
|
|
2307
|
+
resource: `${apiOrigin}/mcp`,
|
|
2308
|
+
authorization_servers: [apiOrigin],
|
|
2309
|
+
scopes_supported: ["mostra"],
|
|
2310
|
+
bearer_methods_supported: ["header"],
|
|
2311
|
+
resource_name: "Mostra"
|
|
2312
|
+
});
|
|
2313
|
+
return;
|
|
2394
2314
|
}
|
|
2395
|
-
|
|
2396
|
-
|
|
2397
|
-
|
|
2398
|
-
|
|
2399
|
-
|
|
2400
|
-
return true;
|
|
2315
|
+
if (method === "POST" && path === "/link") {
|
|
2316
|
+
const who = await bearer(request, "host");
|
|
2317
|
+
if (who && "refused" in who) {
|
|
2318
|
+
send(response, 403, who.refused);
|
|
2319
|
+
return;
|
|
2401
2320
|
}
|
|
2402
|
-
|
|
2403
|
-
|
|
2404
|
-
|
|
2405
|
-
|
|
2406
|
-
const
|
|
2407
|
-
|
|
2408
|
-
|
|
2409
|
-
|
|
2410
|
-
|
|
2411
|
-
|
|
2412
|
-
|
|
2413
|
-
|
|
2321
|
+
if (!who || who.linkId === void 0) {
|
|
2322
|
+
unauthorized(response, "This credential links no instance on this server.");
|
|
2323
|
+
return;
|
|
2324
|
+
}
|
|
2325
|
+
const body = await form(request);
|
|
2326
|
+
const linked = auth.linkState(who.linkId, body?.get("default") === "1");
|
|
2327
|
+
send(response, 200, {
|
|
2328
|
+
account: {
|
|
2329
|
+
id: who.accountId,
|
|
2330
|
+
...who.accountName !== void 0 ? { name: who.accountName } : {}
|
|
2331
|
+
},
|
|
2332
|
+
instanceId: who.linkId,
|
|
2333
|
+
default: linked.default
|
|
2414
2334
|
});
|
|
2415
|
-
|
|
2335
|
+
return;
|
|
2336
|
+
}
|
|
2337
|
+
if (method === "POST" && path === "/oauth/register") {
|
|
2338
|
+
if (!(request.headers["content-type"] ?? "").startsWith("application/json")) {
|
|
2339
|
+
send(response, 400, {
|
|
2340
|
+
error: "invalid_client_metadata",
|
|
2341
|
+
error_description: "Send JSON."
|
|
2342
|
+
});
|
|
2343
|
+
return;
|
|
2344
|
+
}
|
|
2345
|
+
const body = await readBody(request, 65536);
|
|
2346
|
+
let metadata;
|
|
2416
2347
|
try {
|
|
2417
|
-
|
|
2418
|
-
|
|
2419
|
-
|
|
2420
|
-
|
|
2421
|
-
|
|
2422
|
-
|
|
2423
|
-
|
|
2424
|
-
|
|
2425
|
-
|
|
2426
|
-
|
|
2427
|
-
|
|
2428
|
-
|
|
2429
|
-
|
|
2348
|
+
metadata = JSON.parse(body?.toString("utf8") ?? "");
|
|
2349
|
+
} catch {
|
|
2350
|
+
send(response, 400, {
|
|
2351
|
+
error: "invalid_client_metadata",
|
|
2352
|
+
error_description: "Send JSON."
|
|
2353
|
+
});
|
|
2354
|
+
return;
|
|
2355
|
+
}
|
|
2356
|
+
if (options.registrations) {
|
|
2357
|
+
const { addresses, rates } = options.registrations;
|
|
2358
|
+
const taken = rates.take(`register:${addresses.keyOf(addresses.of(request))}`, {
|
|
2359
|
+
count: REGISTRATIONS_PER_MINUTE,
|
|
2360
|
+
perMs: 6e4
|
|
2361
|
+
});
|
|
2362
|
+
if (!taken.ok) {
|
|
2363
|
+
send(response, 429, {
|
|
2364
|
+
error: "slow_down",
|
|
2365
|
+
error_description: "Too many registrations from this address; try again shortly."
|
|
2366
|
+
}, { "retry-after": String(taken.retryAfterS) });
|
|
2367
|
+
return;
|
|
2368
|
+
}
|
|
2369
|
+
}
|
|
2370
|
+
const registered = options.clients.register(metadata);
|
|
2371
|
+
if ("error" in registered && "description" in registered) {
|
|
2372
|
+
send(response, 400, {
|
|
2373
|
+
error: registered["error"],
|
|
2374
|
+
error_description: registered["description"]
|
|
2375
|
+
});
|
|
2376
|
+
return;
|
|
2377
|
+
}
|
|
2378
|
+
send(response, 201, registered);
|
|
2379
|
+
return;
|
|
2380
|
+
}
|
|
2381
|
+
if (method === "GET" && path === "/.well-known/oauth-protected-resource/host") {
|
|
2382
|
+
send(response, 200, {
|
|
2383
|
+
resource: `${apiOrigin}/host`,
|
|
2384
|
+
authorization_servers: [apiOrigin],
|
|
2385
|
+
scopes_supported: ["mostra"]
|
|
2386
|
+
});
|
|
2387
|
+
return;
|
|
2388
|
+
}
|
|
2389
|
+
if (method === "POST" && path === "/oauth/device") {
|
|
2390
|
+
const body = await form(request);
|
|
2391
|
+
if (!body) {
|
|
2392
|
+
send(response, 400, {
|
|
2393
|
+
error: "invalid_request",
|
|
2394
|
+
error_description: "Send a form."
|
|
2395
|
+
});
|
|
2396
|
+
return;
|
|
2397
|
+
}
|
|
2398
|
+
const answer = auth.device(body);
|
|
2399
|
+
if ("error" in answer && typeof answer["status"] === "number") {
|
|
2400
|
+
const failed = answer;
|
|
2401
|
+
send(response, failed.status, {
|
|
2402
|
+
error: failed.error,
|
|
2403
|
+
error_description: failed.description
|
|
2404
|
+
});
|
|
2405
|
+
return;
|
|
2406
|
+
}
|
|
2407
|
+
send(response, 200, answer);
|
|
2408
|
+
return;
|
|
2409
|
+
}
|
|
2410
|
+
if (method === "POST" && path === "/oauth/token") {
|
|
2411
|
+
const body = await form(request);
|
|
2412
|
+
if (!body) {
|
|
2413
|
+
send(response, 400, {
|
|
2414
|
+
error: "invalid_request",
|
|
2415
|
+
error_description: "Send a form."
|
|
2416
|
+
});
|
|
2417
|
+
return;
|
|
2418
|
+
}
|
|
2419
|
+
if (body.get("grant_type") === "refresh_token") {
|
|
2420
|
+
const account = auth.refreshAccount(body.get("refresh_token") ?? "");
|
|
2421
|
+
if (account !== void 0) await accountStanding(account);
|
|
2422
|
+
}
|
|
2423
|
+
const answer = auth.token(body);
|
|
2424
|
+
if ("error" in answer) {
|
|
2425
|
+
send(response, answer.status, {
|
|
2426
|
+
error: answer.error,
|
|
2427
|
+
error_description: answer.description
|
|
2428
|
+
});
|
|
2429
|
+
return;
|
|
2430
|
+
}
|
|
2431
|
+
send(response, 200, answer);
|
|
2432
|
+
return;
|
|
2433
|
+
}
|
|
2434
|
+
if (method === "POST" && path === "/oauth/revoke") {
|
|
2435
|
+
const body = await form(request);
|
|
2436
|
+
if (body) auth.revoke(body);
|
|
2437
|
+
send(response, 200, {});
|
|
2438
|
+
return;
|
|
2439
|
+
}
|
|
2440
|
+
if (method === "POST" && path === "/_mostra/appearance") {
|
|
2441
|
+
const body = request.headers.origin === apiOrigin ? await form(request) : void 0;
|
|
2442
|
+
const chosen = body?.get("appearance");
|
|
2443
|
+
const next = body?.get("next") ?? "/";
|
|
2444
|
+
const back = next.startsWith("/") && !next.startsWith("//") && !next.startsWith("/\\") ? next : "/";
|
|
2445
|
+
response.writeHead(303, {
|
|
2446
|
+
...BASE_HEADERS,
|
|
2447
|
+
location: back,
|
|
2448
|
+
...chosen === "light" || chosen === "dark" || chosen === "system" ? { "set-cookie": appearanceCookie(chosen, apiOrigin.startsWith("https:")) } : {}
|
|
2449
|
+
});
|
|
2450
|
+
response.end();
|
|
2451
|
+
return;
|
|
2452
|
+
}
|
|
2453
|
+
if (path === "/device") {
|
|
2454
|
+
const provider = developmentProvider$1(config);
|
|
2455
|
+
const signed = options.authorize.sessionAccount(request);
|
|
2456
|
+
if (method === "GET") {
|
|
2457
|
+
const code = new URL(request.url ?? "/", apiOrigin).searchParams.get("user_code") ?? "";
|
|
2458
|
+
if (signed) {
|
|
2459
|
+
page(response, 200, sessionDevicePage(response, code, signed));
|
|
2460
|
+
return;
|
|
2461
|
+
}
|
|
2462
|
+
if (!await devFormOffered()) {
|
|
2463
|
+
await options.authorize.signInPage(response, `/device?user_code=${encodeURIComponent(code)}`);
|
|
2464
|
+
return;
|
|
2465
|
+
}
|
|
2466
|
+
page(response, 200, devicePage(response, {
|
|
2467
|
+
code,
|
|
2468
|
+
provider
|
|
2469
|
+
}));
|
|
2470
|
+
return;
|
|
2471
|
+
}
|
|
2472
|
+
let posted;
|
|
2473
|
+
if (method === "POST" && signed && request.headers.origin === apiOrigin) {
|
|
2474
|
+
const body = await form(request);
|
|
2475
|
+
posted = body;
|
|
2476
|
+
const decision = body?.get("session_decision");
|
|
2477
|
+
if (body && decision !== null && decision !== void 0) {
|
|
2478
|
+
const code = body.get("user_code") ?? "";
|
|
2479
|
+
if (body.get("csrf") !== options.authorize.csrf(signed.hash, "device")) {
|
|
2480
|
+
page(response, 403, devicePage(response, {
|
|
2481
|
+
code: "",
|
|
2482
|
+
provider,
|
|
2483
|
+
message: "This form must be sent from this page."
|
|
2484
|
+
}));
|
|
2485
|
+
return;
|
|
2486
|
+
}
|
|
2487
|
+
const approve = decision === "approve";
|
|
2488
|
+
const decided = auth.decideFor({
|
|
2489
|
+
code,
|
|
2490
|
+
approve,
|
|
2491
|
+
accountId: signed.accountId
|
|
2492
|
+
});
|
|
2493
|
+
page(response, decided.ok ? 200 : 400, devicePage(response, {
|
|
2494
|
+
code,
|
|
2495
|
+
provider,
|
|
2496
|
+
...decided.ok ? {
|
|
2497
|
+
done: true,
|
|
2498
|
+
message: approve ? "The machine is linked to your account." : "The sign-in was refused."
|
|
2499
|
+
} : { message: decided.reason }
|
|
2500
|
+
}));
|
|
2501
|
+
return;
|
|
2502
|
+
}
|
|
2503
|
+
}
|
|
2504
|
+
if (method === "POST") {
|
|
2505
|
+
if (request.headers.origin !== apiOrigin) {
|
|
2506
|
+
page(response, 403, devicePage(response, {
|
|
2507
|
+
code: "",
|
|
2508
|
+
provider,
|
|
2509
|
+
message: "This form must be sent from this page."
|
|
2510
|
+
}));
|
|
2511
|
+
return;
|
|
2512
|
+
}
|
|
2513
|
+
const body = posted ?? await form(request);
|
|
2514
|
+
const code = body?.get("user_code") ?? "";
|
|
2515
|
+
const name = (body?.get("name") ?? "").trim().slice(0, 64);
|
|
2516
|
+
if (!body || !provider || !await devFormOffered() || body.get("provider") !== provider.id || name === "") {
|
|
2517
|
+
page(response, 400, devicePage(response, {
|
|
2518
|
+
code,
|
|
2519
|
+
provider,
|
|
2520
|
+
message: "Enter the code and your name."
|
|
2521
|
+
}));
|
|
2522
|
+
return;
|
|
2523
|
+
}
|
|
2524
|
+
const approve = body.get("decision") === "approve";
|
|
2525
|
+
const pending = auth.pendingCode(code);
|
|
2526
|
+
if (!pending.ok) {
|
|
2527
|
+
page(response, 400, devicePage(response, {
|
|
2528
|
+
code,
|
|
2529
|
+
provider,
|
|
2530
|
+
message: pending.reason
|
|
2531
|
+
}));
|
|
2532
|
+
return;
|
|
2533
|
+
}
|
|
2534
|
+
const identity = {
|
|
2430
2535
|
provider: provider.id,
|
|
2431
|
-
|
|
2536
|
+
subject: name.toLowerCase(),
|
|
2537
|
+
name
|
|
2538
|
+
};
|
|
2539
|
+
let decided;
|
|
2540
|
+
if (!approve) decided = auth.decide({
|
|
2541
|
+
code,
|
|
2542
|
+
approve: false,
|
|
2543
|
+
identity
|
|
2432
2544
|
});
|
|
2433
|
-
|
|
2434
|
-
|
|
2545
|
+
else {
|
|
2546
|
+
const account = await auth.resolveAccount(identity, 0);
|
|
2547
|
+
if (account.kind !== "account") {
|
|
2548
|
+
const reason = account.kind === "unavailable" ? "Sign-in is unavailable for a moment; try again shortly." : account.kind === "refused" ? account.message : account.kind === "suspended" ? "This account is suspended." : "This server asks for a step before a first sign-in, which the development sign-in can't take.";
|
|
2549
|
+
page(response, account.kind === "unavailable" ? 503 : 403, devicePage(response, {
|
|
2550
|
+
code,
|
|
2551
|
+
provider,
|
|
2552
|
+
message: reason
|
|
2553
|
+
}));
|
|
2554
|
+
return;
|
|
2555
|
+
}
|
|
2556
|
+
decided = auth.decideFor({
|
|
2557
|
+
code,
|
|
2558
|
+
approve: true,
|
|
2559
|
+
accountId: account.accountId
|
|
2560
|
+
});
|
|
2561
|
+
}
|
|
2562
|
+
if (!decided.ok) {
|
|
2563
|
+
page(response, 400, devicePage(response, {
|
|
2564
|
+
code,
|
|
2565
|
+
provider,
|
|
2566
|
+
message: decided.reason
|
|
2567
|
+
}));
|
|
2568
|
+
return;
|
|
2569
|
+
}
|
|
2570
|
+
page(response, 200, devicePage(response, {
|
|
2571
|
+
code,
|
|
2572
|
+
provider,
|
|
2573
|
+
done: true,
|
|
2574
|
+
message: approve ? "The machine is linked to your account." : "The sign-in was refused."
|
|
2575
|
+
}));
|
|
2576
|
+
return;
|
|
2435
2577
|
}
|
|
2436
|
-
redirect(response, target, { "set-cookie": setCookie(flowCookie, flow, Math.floor(PENDING_MS / 1e3)) });
|
|
2437
|
-
return true;
|
|
2438
2578
|
}
|
|
2439
|
-
|
|
2440
|
-
|
|
2441
|
-
|
|
2442
|
-
|
|
2443
|
-
|
|
2444
|
-
|
|
2445
|
-
|
|
2446
|
-
|
|
2579
|
+
if (path === "/mcp" && options.mcp) {
|
|
2580
|
+
const who = await bearer(request, "mcp");
|
|
2581
|
+
const challenge = `Bearer resource_metadata="${apiOrigin}/.well-known/oauth-protected-resource/mcp"`;
|
|
2582
|
+
if (!who) {
|
|
2583
|
+
send(response, 401, {
|
|
2584
|
+
error: "invalid_token",
|
|
2585
|
+
error_description: "Sign in to use Mostra here."
|
|
2586
|
+
}, { "www-authenticate": challenge });
|
|
2587
|
+
return;
|
|
2447
2588
|
}
|
|
2448
|
-
if (
|
|
2449
|
-
|
|
2450
|
-
|
|
2451
|
-
<form method="post" action="/signin/${escapeHtml(id)}/name"><input type="hidden" name="state" value="${escapeHtml(state)}">
|
|
2452
|
-
<label>Your name <input name="name" required maxlength="64"></label> <button>Continue</button></form>`));
|
|
2453
|
-
return true;
|
|
2589
|
+
if ("refused" in who) {
|
|
2590
|
+
send(response, 403, who.refused);
|
|
2591
|
+
return;
|
|
2454
2592
|
}
|
|
2455
|
-
|
|
2456
|
-
|
|
2457
|
-
|
|
2458
|
-
|
|
2459
|
-
|
|
2460
|
-
|
|
2461
|
-
}
|
|
2462
|
-
params = Object.fromEntries(form.entries());
|
|
2463
|
-
} else {
|
|
2464
|
-
params = {};
|
|
2465
|
-
for (const key of new Set(url.searchParams.keys())) {
|
|
2466
|
-
if (url.searchParams.getAll(key).length > 1) {
|
|
2467
|
-
problem(response, 400, `The provider's answer names ${key} twice.`);
|
|
2468
|
-
return true;
|
|
2469
|
-
}
|
|
2470
|
-
params[key] = url.searchParams.get(key);
|
|
2471
|
-
}
|
|
2593
|
+
if (!who.scope.split(" ").includes("mostra")) {
|
|
2594
|
+
send(response, 403, {
|
|
2595
|
+
error: "insufficient_scope",
|
|
2596
|
+
error_description: "The token lacks the mostra scope."
|
|
2597
|
+
}, { "www-authenticate": `${challenge}, error="insufficient_scope", scope="mostra"` });
|
|
2598
|
+
return;
|
|
2472
2599
|
}
|
|
2473
|
-
|
|
2474
|
-
|
|
2475
|
-
|
|
2476
|
-
|
|
2477
|
-
|
|
2478
|
-
|
|
2600
|
+
await options.mcp.handle(request, response, who);
|
|
2601
|
+
return;
|
|
2602
|
+
}
|
|
2603
|
+
const file = /^\/files\/([0-9a-f]{64})$/.exec(path);
|
|
2604
|
+
if (file && method === "PUT") {
|
|
2605
|
+
await upload(request, response, file[1]);
|
|
2606
|
+
return;
|
|
2607
|
+
}
|
|
2608
|
+
send(response, 404, {
|
|
2609
|
+
code: "MOSTRA_HYGIENE_NOT_SERVED",
|
|
2610
|
+
message: "Nothing is served at this path."
|
|
2611
|
+
});
|
|
2612
|
+
},
|
|
2613
|
+
upgrade(request, socket, head, path) {
|
|
2614
|
+
const refuse = (status, text, extra = "") => {
|
|
2615
|
+
socket.end(`HTTP/1.1 ${status} ${text}\r\nconnection: close\r\ncontent-length: 0\r\n${extra}\r\n`);
|
|
2616
|
+
};
|
|
2617
|
+
if (path !== "/host") {
|
|
2618
|
+
refuse(404, "Not Found");
|
|
2619
|
+
return;
|
|
2620
|
+
}
|
|
2621
|
+
bearer(request, "host").then((who) => upgradeFor(who), (error) => {
|
|
2622
|
+
log.error("binding.auth_failed", { error });
|
|
2623
|
+
refuse(503, "Service Unavailable");
|
|
2624
|
+
});
|
|
2625
|
+
const upgradeFor = (who) => {
|
|
2626
|
+
if (who && "refused" in who) {
|
|
2627
|
+
refuse(403, "Forbidden");
|
|
2628
|
+
return;
|
|
2479
2629
|
}
|
|
2480
|
-
|
|
2481
|
-
|
|
2482
|
-
|
|
2483
|
-
|
|
2484
|
-
|
|
2485
|
-
|
|
2486
|
-
|
|
2487
|
-
|
|
2488
|
-
|
|
2489
|
-
|
|
2490
|
-
|
|
2491
|
-
|
|
2492
|
-
|
|
2493
|
-
|
|
2494
|
-
|
|
2630
|
+
if (!who) {
|
|
2631
|
+
refuse(401, "Unauthorized", `www-authenticate: Bearer resource_metadata="${apiOrigin}/.well-known/oauth-protected-resource/host"\r\n`);
|
|
2632
|
+
return;
|
|
2633
|
+
}
|
|
2634
|
+
options.home(who.homeId).then((home) => {
|
|
2635
|
+
sockets.handleUpgrade(request, socket, head, (ws) => {
|
|
2636
|
+
bindings.add(ws);
|
|
2637
|
+
bindingHomes.set(ws, who.homeId);
|
|
2638
|
+
let expiresAt = who.expiresAt;
|
|
2639
|
+
const attributes = {
|
|
2640
|
+
accountId: who.accountId,
|
|
2641
|
+
grantId: who.grantId,
|
|
2642
|
+
homeId: who.homeId,
|
|
2643
|
+
linkId: who.linkId,
|
|
2644
|
+
replaceToken: (next) => {
|
|
2645
|
+
expiresAt = next;
|
|
2646
|
+
}
|
|
2647
|
+
};
|
|
2648
|
+
const watch = setInterval(() => {
|
|
2649
|
+
if (Date.now() >= expiresAt) {
|
|
2650
|
+
log.info("binding.token_expired", { home: who.homeId });
|
|
2651
|
+
ws.close(4401, "token expired");
|
|
2652
|
+
} else if (who.grantId.startsWith("credential:")) bearer(request, "host").then((still) => {
|
|
2653
|
+
if (!still || "refused" in still) {
|
|
2654
|
+
log.info("binding.credential_revoked", { home: who.homeId });
|
|
2655
|
+
ws.close(4403, "credential revoked");
|
|
2656
|
+
} else expiresAt = still.expiresAt;
|
|
2657
|
+
}, () => void 0);
|
|
2658
|
+
else if (!auth.grantLive(who.grantId)) {
|
|
2659
|
+
log.info("binding.grant_revoked", { home: who.homeId });
|
|
2660
|
+
ws.close(4403, "grant revoked");
|
|
2661
|
+
} else standing(who).then((refused) => {
|
|
2662
|
+
if (refused) {
|
|
2663
|
+
log.info("binding.account_suspended", { home: who.homeId });
|
|
2664
|
+
ws.close(4403, "account suspended");
|
|
2665
|
+
}
|
|
2666
|
+
}, () => void 0);
|
|
2667
|
+
}, Math.min(GRANT_RECHECK_MS, options.recheckMs ?? GRANT_RECHECK_MS));
|
|
2668
|
+
watch.unref();
|
|
2669
|
+
ws.once("close", () => {
|
|
2670
|
+
clearInterval(watch);
|
|
2671
|
+
bindings.delete(ws);
|
|
2672
|
+
bindingHomes.delete(ws);
|
|
2673
|
+
});
|
|
2674
|
+
ws.on("message", () => {
|
|
2675
|
+
options.touch(who.homeId);
|
|
2676
|
+
options.message?.(who.homeId);
|
|
2677
|
+
});
|
|
2678
|
+
serveWebSocket(home.protocol, ws, {
|
|
2679
|
+
attributes,
|
|
2680
|
+
log
|
|
2681
|
+
});
|
|
2682
|
+
log.info("binding.opened", {
|
|
2683
|
+
home: who.homeId,
|
|
2684
|
+
link: who.linkId
|
|
2685
|
+
});
|
|
2495
2686
|
});
|
|
2496
|
-
|
|
2497
|
-
|
|
2498
|
-
|
|
2499
|
-
|
|
2500
|
-
provider: provider.id,
|
|
2501
|
-
message: error.message
|
|
2687
|
+
}, (error) => {
|
|
2688
|
+
log.error("binding.home_failed", {
|
|
2689
|
+
home: who.homeId,
|
|
2690
|
+
error
|
|
2502
2691
|
});
|
|
2503
|
-
|
|
2504
|
-
|
|
2505
|
-
|
|
2506
|
-
|
|
2507
|
-
|
|
2508
|
-
|
|
2509
|
-
|
|
2510
|
-
|
|
2511
|
-
|
|
2512
|
-
|
|
2513
|
-
if (!step || flow === void 0 || hashSecret(flow) !== step.flow || !spend(handle)) {
|
|
2514
|
-
problem(response, 400, "This sign-in step expired, was used, or belongs to another browser.");
|
|
2515
|
-
return true;
|
|
2516
|
-
}
|
|
2517
|
-
await resolved(response, step.identity, step.verifiedBy, step.steps, step.flow, step.next);
|
|
2518
|
-
return true;
|
|
2519
|
-
}
|
|
2520
|
-
return false;
|
|
2692
|
+
refuse(503, "Service Unavailable");
|
|
2693
|
+
});
|
|
2694
|
+
};
|
|
2695
|
+
},
|
|
2696
|
+
closeHome(homeId) {
|
|
2697
|
+
for (const [ws, home] of bindingHomes) if (home === homeId) ws.close(4403, "home unavailable");
|
|
2698
|
+
},
|
|
2699
|
+
close() {
|
|
2700
|
+
for (const ws of bindings) ws.terminate();
|
|
2701
|
+
sockets.close();
|
|
2521
2702
|
}
|
|
2522
2703
|
};
|
|
2523
2704
|
}
|
|
@@ -4782,7 +4963,19 @@ async function openHostedHome(options) {
|
|
|
4782
4963
|
latestVersion: (artifactId) => ledger.read((db) => db.get("SELECT latest_version_id FROM artifact WHERE id = ?", artifactId)?.latest_version_id ?? void 0),
|
|
4783
4964
|
storeLive: (artifactId, versionId, produced) => live.relayed(artifactId, versionId, produced)
|
|
4784
4965
|
});
|
|
4966
|
+
/** A page's live reads: they ask the owner for producers, and say when it is away. */
|
|
4967
|
+
const hostedLive = { read(page, input) {
|
|
4968
|
+
const states = live.read(page, input);
|
|
4969
|
+
relay.liveWanted(page.artifactId);
|
|
4970
|
+
if (!relay.ownerOffline(page.artifactId)) return states;
|
|
4971
|
+
return states.map((state) => state.key.startsWith("$tally/") ? state : {
|
|
4972
|
+
...state,
|
|
4973
|
+
ownerOffline: true
|
|
4974
|
+
});
|
|
4975
|
+
} };
|
|
4976
|
+
const pages = options.services?.pages?.();
|
|
4785
4977
|
const gateway = createGateway({
|
|
4978
|
+
...pages ? { pages } : {},
|
|
4786
4979
|
ledger,
|
|
4787
4980
|
log,
|
|
4788
4981
|
addressing,
|
|
@@ -4797,15 +4990,7 @@ async function openHostedHome(options) {
|
|
|
4797
4990
|
bus,
|
|
4798
4991
|
linkLimit: (artifactId, count) => linkLimit(artifactId, count),
|
|
4799
4992
|
actions: relay,
|
|
4800
|
-
live:
|
|
4801
|
-
const states = live.read(page, input);
|
|
4802
|
-
relay.liveWanted(page.artifactId);
|
|
4803
|
-
if (!relay.ownerOffline(page.artifactId)) return states;
|
|
4804
|
-
return states.map((state) => state.key.startsWith("$tally/") ? state : {
|
|
4805
|
-
...state,
|
|
4806
|
-
ownerOffline: true
|
|
4807
|
-
});
|
|
4808
|
-
} },
|
|
4993
|
+
live: hostedLive,
|
|
4809
4994
|
controls: async () => ({ submitChannels: ["shell", "artifact"] }),
|
|
4810
4995
|
activated: () => void 0,
|
|
4811
4996
|
hosted: {
|
|
@@ -6516,8 +6701,37 @@ function json(response, status, body) {
|
|
|
6516
6701
|
});
|
|
6517
6702
|
response.end(text);
|
|
6518
6703
|
}
|
|
6519
|
-
|
|
6520
|
-
|
|
6704
|
+
/** Whether a request is a person's navigation, answered with a page rather than JSON. */
|
|
6705
|
+
function wantsPage(request) {
|
|
6706
|
+
if (!request) return false;
|
|
6707
|
+
const dest = request.headers["sec-fetch-dest"];
|
|
6708
|
+
if (typeof dest === "string") return dest === "document";
|
|
6709
|
+
return (request.headers.accept ?? "").includes("text/html");
|
|
6710
|
+
}
|
|
6711
|
+
/**
|
|
6712
|
+
* A refusal: a page in the server's theme for a person's navigation (an unknown host, a request
|
|
6713
|
+
* the server couldn't answer), the diagnostic as JSON for anything else.
|
|
6714
|
+
*/
|
|
6715
|
+
function refusal$1(response, status, diagnostic, pages = defaultPages()) {
|
|
6716
|
+
const request = response.req;
|
|
6717
|
+
if (!wantsPage(request)) {
|
|
6718
|
+
json(response, status, diagnostic);
|
|
6719
|
+
return;
|
|
6720
|
+
}
|
|
6721
|
+
const text = refusalDocument(pages.pages, {
|
|
6722
|
+
title: diagnostic.message,
|
|
6723
|
+
detail: diagnostic.hint,
|
|
6724
|
+
code: diagnostic.code
|
|
6725
|
+
});
|
|
6726
|
+
response.writeHead(status, {
|
|
6727
|
+
...BASE_HEADERS$1,
|
|
6728
|
+
"content-type": "text/html; charset=utf-8",
|
|
6729
|
+
"content-length": String(Buffer.byteLength(text)),
|
|
6730
|
+
"cache-control": "no-store",
|
|
6731
|
+
"content-security-policy": themePageCsp(pages.pages),
|
|
6732
|
+
"x-frame-options": "DENY"
|
|
6733
|
+
});
|
|
6734
|
+
response.end(request?.method === "HEAD" ? void 0 : text);
|
|
6521
6735
|
}
|
|
6522
6736
|
/** Splits `host:port`, with `[::1]:port` for IPv6. */
|
|
6523
6737
|
function parseListen(listen) {
|
|
@@ -6532,6 +6746,7 @@ function parseListen(listen) {
|
|
|
6532
6746
|
async function startServer(options) {
|
|
6533
6747
|
const { config, log } = options;
|
|
6534
6748
|
let auth;
|
|
6749
|
+
let pagesOfHosts = defaultPages();
|
|
6535
6750
|
let operator;
|
|
6536
6751
|
let meter;
|
|
6537
6752
|
let routing;
|
|
@@ -6588,7 +6803,9 @@ async function startServer(options) {
|
|
|
6588
6803
|
start: (signin, challenge) => authorizer.startViewerSignin(signin, challenge),
|
|
6589
6804
|
finish: (input) => authorizer.finishViewerSignin(input)
|
|
6590
6805
|
},
|
|
6591
|
-
signInOffered: () => (config.identityProviders?.length ?? 0) > 0 || (operator?.has.identity ?? false)
|
|
6806
|
+
signInOffered: () => (config.identityProviders?.length ?? 0) > 0 || (operator?.has.identity ?? false),
|
|
6807
|
+
madeWith: { href: MADE_WITH_HREF },
|
|
6808
|
+
pages: () => pagesOfHosts
|
|
6592
6809
|
});
|
|
6593
6810
|
const data = await openDataDirectory({
|
|
6594
6811
|
dir: options.data,
|
|
@@ -6725,7 +6942,20 @@ async function startServer(options) {
|
|
|
6725
6942
|
await data.close();
|
|
6726
6943
|
throw error;
|
|
6727
6944
|
}
|
|
6945
|
+
let apiPages;
|
|
6946
|
+
let hostedPages;
|
|
6947
|
+
try {
|
|
6948
|
+
apiPages = serverPages(config.appearance, { appearanceAction: APPEARANCE_PATH });
|
|
6949
|
+
hostedPages = serverPages(config.appearance);
|
|
6950
|
+
} catch (error) {
|
|
6951
|
+
operator?.stop();
|
|
6952
|
+
await data.close();
|
|
6953
|
+
throw new RpcError(createDiagnostic("MOSTRA_REMOTE_CONFIG_INVALID", { message: `The configuration key \`appearance.logo\` can't be used: ${error.message}` }));
|
|
6954
|
+
}
|
|
6955
|
+
pagesOfHosts = hostedPages;
|
|
6728
6956
|
const authorize = createAuthorize({
|
|
6957
|
+
server: apiPages,
|
|
6958
|
+
pages: createApiPages(apiPages, apiPages.name),
|
|
6729
6959
|
apiOrigin: config.apiOrigin,
|
|
6730
6960
|
directory: data.directory,
|
|
6731
6961
|
auth,
|
|
@@ -6747,6 +6977,7 @@ async function startServer(options) {
|
|
|
6747
6977
|
ensureHome: (accountId) => auth.ensureHome(accountId)
|
|
6748
6978
|
});
|
|
6749
6979
|
api = createApi({
|
|
6980
|
+
server: apiPages,
|
|
6750
6981
|
config,
|
|
6751
6982
|
auth,
|
|
6752
6983
|
mcp,
|
|
@@ -6779,6 +7010,17 @@ async function startServer(options) {
|
|
|
6779
7010
|
const host = (request.headers.host ?? "").toLowerCase();
|
|
6780
7011
|
const path = (request.url ?? "/").split("?")[0] ?? "/";
|
|
6781
7012
|
if (host !== apiHost) delete request.headers.cookie;
|
|
7013
|
+
if ((request.method === "GET" || request.method === "HEAD") && path.startsWith("/_mostra/theme/")) {
|
|
7014
|
+
const file = pagesOfHosts.asset(path.slice(THEME_BASE.length));
|
|
7015
|
+
if (file) {
|
|
7016
|
+
response.writeHead(200, {
|
|
7017
|
+
...BASE_HEADERS$1,
|
|
7018
|
+
...file.headers
|
|
7019
|
+
});
|
|
7020
|
+
response.end(request.method === "HEAD" ? void 0 : file.body);
|
|
7021
|
+
return;
|
|
7022
|
+
}
|
|
7023
|
+
}
|
|
6782
7024
|
if (host === apiHost && request.method === "GET" && path === "/health") {
|
|
6783
7025
|
json(response, 200, {
|
|
6784
7026
|
status: "ok",
|
|
@@ -6805,7 +7047,7 @@ async function startServer(options) {
|
|
|
6805
7047
|
});
|
|
6806
7048
|
return;
|
|
6807
7049
|
}
|
|
6808
|
-
const hostRefused = () => refusal$1(response, 421, createDiagnostic("MOSTRA_HYGIENE_HOST_REFUSED", { message: "This server serves no pages at this host." }));
|
|
7050
|
+
const hostRefused = () => refusal$1(response, 421, createDiagnostic("MOSTRA_HYGIENE_HOST_REFUSED", { message: "This server serves no pages at this host." }), pagesOfHosts);
|
|
6809
7051
|
if (!/^[a-z0-9.-]{1,253}(:\d{1,5})?$/.test(host)) {
|
|
6810
7052
|
hostRefused();
|
|
6811
7053
|
return;
|