@mostra/runtime 0.8.0 → 0.10.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 +2879 -8
- package/dist/bin.js.map +1 -1
- package/dist/builder/child/main.js +2 -2
- package/dist/{child-Chiavhdx.js → child-BmNZ4a70.js} +2 -2
- package/dist/{child-Chiavhdx.js.map → child-BmNZ4a70.js.map} +1 -1
- package/dist/deps/child/install.js +1 -1
- package/dist/{directories-mJ1qlVht.js → directories-BLJjeSPD.js} +5 -5
- package/dist/directories-BLJjeSPD.js.map +1 -0
- package/dist/{files-FygSJIzK.js → files-DGeWuE4I.js} +2 -2
- package/dist/{files-FygSJIzK.js.map → files-DGeWuE4I.js.map} +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/{instance-BRfg27Rg.js → instance-FExcyENK.js} +3346 -395
- package/dist/instance-FExcyENK.js.map +1 -0
- package/package.json +7 -5
- package/src/actions/index.ts +163 -10
- package/src/bin.ts +78 -1
- package/src/gateway/actions.ts +20 -4
- package/src/gateway/browser.ts +118 -95
- package/src/gateway/capabilities.ts +15 -6
- package/src/gateway/index.ts +112 -15
- package/src/gateway/routes.ts +15 -7
- package/src/gc/index.ts +14 -0
- package/src/instance/index.ts +41 -2
- package/src/interaction/ephemeral.ts +32 -23
- package/src/interaction/events.ts +21 -1
- package/src/interaction/imports.ts +317 -0
- package/src/interaction/index.ts +172 -19
- package/src/interaction/outbox.ts +9 -0
- package/src/interaction/results.ts +22 -1
- package/src/interaction/runs.ts +52 -2
- package/src/interaction/submissions.ts +17 -1
- package/src/interaction/tally.ts +129 -0
- package/src/ledger/index.ts +104 -9
- package/src/ledger/migrations.ts +183 -0
- package/src/ledger/types.ts +8 -0
- package/src/link/binding.ts +289 -0
- package/src/link/hosted.ts +65 -0
- package/src/link/http.ts +136 -0
- package/src/link/index.ts +8 -0
- package/src/link/manager.ts +1385 -0
- package/src/link/relay.ts +512 -0
- package/src/live/index.ts +112 -2
- package/src/platform/filesystems.ts +78 -0
- package/src/platform/index.ts +1 -0
- package/src/protocol-server/index.ts +18 -1
- package/src/protocol-server/server.ts +38 -7
- package/src/protocol-server/websocket.ts +161 -0
- package/src/publish/bundle.ts +398 -0
- package/src/publish/manifest.ts +9 -0
- package/src/publish/methods.ts +12 -1
- package/src/publish/publisher.ts +127 -0
- package/src/registry/index.ts +35 -14
- package/src/server/api.ts +439 -0
- package/src/server/auth.ts +613 -0
- package/src/server/config.ts +221 -0
- package/src/server/data.ts +369 -0
- package/src/server/directory.ts +141 -0
- package/src/server/hosted.ts +822 -0
- package/src/server/index.ts +368 -0
- package/src/server/relay.ts +1163 -0
- package/src/share/index.ts +110 -6
- package/dist/directories-mJ1qlVht.js.map +0 -1
- package/dist/instance-BRfg27Rg.js.map +0 -1
package/src/registry/index.ts
CHANGED
|
@@ -56,8 +56,16 @@ const VERSION_ROWS =
|
|
|
56
56
|
export interface VersionCommit {
|
|
57
57
|
/** The artifact the publish resolved before building. */
|
|
58
58
|
readonly artifactId: string;
|
|
59
|
-
/**
|
|
60
|
-
|
|
59
|
+
/**
|
|
60
|
+
* The real path of the source (D51); absent for a version imported from a bundle (RM-01),
|
|
61
|
+
* which binds no path in this home.
|
|
62
|
+
*/
|
|
63
|
+
readonly bindingPath: string | undefined;
|
|
64
|
+
/**
|
|
65
|
+
* The number a new version takes when the artifact has no version of that number yet: an
|
|
66
|
+
* imported bundle keeps its number (RM-01, D165 item 3). Absent: the next number.
|
|
67
|
+
*/
|
|
68
|
+
readonly number?: number;
|
|
61
69
|
/** The manifest's `id`, when it has one. */
|
|
62
70
|
readonly manifestId: string | undefined;
|
|
63
71
|
readonly versionId: string;
|
|
@@ -229,7 +237,7 @@ export async function openRegistry(options: {
|
|
|
229
237
|
const now = new Date().toISOString();
|
|
230
238
|
// Identity (D51): the manifest's id wins; a path bound elsewhere follows it; a moved source
|
|
231
239
|
// rebinds; a copy that still claims the id is a conflict.
|
|
232
|
-
if (input.manifestId !== undefined) {
|
|
240
|
+
if (input.manifestId !== undefined && input.bindingPath !== undefined) {
|
|
233
241
|
const others = db.all<{ path: string }>(
|
|
234
242
|
"SELECT path FROM source_binding WHERE artifact_id = ? AND path != ?",
|
|
235
243
|
input.manifestId,
|
|
@@ -245,7 +253,9 @@ export async function openRegistry(options: {
|
|
|
245
253
|
}
|
|
246
254
|
}
|
|
247
255
|
const resolved =
|
|
248
|
-
input.manifestId ??
|
|
256
|
+
input.manifestId ??
|
|
257
|
+
(input.bindingPath === undefined ? undefined : boundArtifact(db, input.bindingPath)) ??
|
|
258
|
+
input.artifactId;
|
|
249
259
|
if (resolved !== input.artifactId) {
|
|
250
260
|
throw new RpcError(
|
|
251
261
|
createDiagnostic("MOSTRA_PUBLISH_SOURCE_CHANGED", {
|
|
@@ -295,11 +305,20 @@ export async function openRegistry(options: {
|
|
|
295
305
|
} else {
|
|
296
306
|
if (input.outputDigest === undefined)
|
|
297
307
|
throw new Error("A new version needs its output digest.");
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
308
|
+
const free =
|
|
309
|
+
input.number !== undefined &&
|
|
310
|
+
db.get(
|
|
311
|
+
"SELECT 1 FROM version WHERE artifact_id = ? AND number = ?",
|
|
301
312
|
input.artifactId,
|
|
302
|
-
|
|
313
|
+
input.number,
|
|
314
|
+
) === undefined;
|
|
315
|
+
number =
|
|
316
|
+
free && input.number !== undefined
|
|
317
|
+
? input.number
|
|
318
|
+
: (db.get<{ next: number }>(
|
|
319
|
+
"SELECT COALESCE(MAX(number), 0) + 1 AS next FROM version WHERE artifact_id = ?",
|
|
320
|
+
input.artifactId,
|
|
321
|
+
)?.next ?? 1);
|
|
303
322
|
db.run(
|
|
304
323
|
"INSERT INTO version (id, artifact_id, number, source_digest, env_digest, output_digest, manifest_json, forced_codes_json, published_at, verify_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
|
305
324
|
input.versionId,
|
|
@@ -348,12 +367,14 @@ export async function openRegistry(options: {
|
|
|
348
367
|
input.versionId,
|
|
349
368
|
input.artifactId,
|
|
350
369
|
);
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
370
|
+
if (input.bindingPath !== undefined) {
|
|
371
|
+
db.run(
|
|
372
|
+
"INSERT INTO source_binding (path, artifact_id, bound_at) VALUES (?, ?, ?) ON CONFLICT(path) DO UPDATE SET artifact_id = excluded.artifact_id, bound_at = excluded.bound_at",
|
|
373
|
+
input.bindingPath,
|
|
374
|
+
input.artifactId,
|
|
375
|
+
now,
|
|
376
|
+
);
|
|
377
|
+
}
|
|
357
378
|
input.inTransaction?.(db);
|
|
358
379
|
const committed = { version: number, cursor, reused: existing !== undefined };
|
|
359
380
|
if (input.request !== undefined) {
|
|
@@ -0,0 +1,439 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The remote server's API origin (INTERFACES §18.2, §18.5): the authorization server's device
|
|
3
|
+
* grant (`/oauth/device`, `/oauth/token`, `/oauth/revoke`, its metadata and the device page), the
|
|
4
|
+
* network binding (`/host`, JSON-RPC over WebSocket with a bearer token) and version files
|
|
5
|
+
* (`PUT /files/<sha256>`). Never on a user-content domain (D165 item 7).
|
|
6
|
+
*/
|
|
7
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
8
|
+
import { createWriteStream, existsSync, renameSync } from "node:fs";
|
|
9
|
+
import { rm } from "node:fs/promises";
|
|
10
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
11
|
+
import { join } from "node:path";
|
|
12
|
+
import type { Duplex } from "node:stream";
|
|
13
|
+
import { type WebSocket, WebSocketServer } from "ws";
|
|
14
|
+
import type { Log } from "../log.ts";
|
|
15
|
+
import { BINDING_SUBPROTOCOL, MAX_FRAME_BYTES, serveWebSocket } from "../protocol-server/index.ts";
|
|
16
|
+
import type { Authenticated, Authorization } from "./auth.ts";
|
|
17
|
+
import type { RemoteServerConfig } from "./config.ts";
|
|
18
|
+
import type { HostedHome } from "./hosted.ts";
|
|
19
|
+
|
|
20
|
+
/** How often an open binding's grant is checked again: a revocation closes it within 60 s. */
|
|
21
|
+
const GRANT_RECHECK_MS = 30_000;
|
|
22
|
+
|
|
23
|
+
/** The largest version file accepted (per file; an operator's storage limit is WP-30's). */
|
|
24
|
+
const MAX_FILE_BYTES = 256 * 1024 * 1024;
|
|
25
|
+
|
|
26
|
+
const BASE_HEADERS = {
|
|
27
|
+
"cache-control": "no-store",
|
|
28
|
+
"cross-origin-resource-policy": "same-origin",
|
|
29
|
+
"referrer-policy": "no-referrer",
|
|
30
|
+
"x-content-type-options": "nosniff",
|
|
31
|
+
} as const;
|
|
32
|
+
|
|
33
|
+
function send(
|
|
34
|
+
response: ServerResponse,
|
|
35
|
+
status: number,
|
|
36
|
+
body: unknown,
|
|
37
|
+
headers: Record<string, string> = {},
|
|
38
|
+
): void {
|
|
39
|
+
const text = JSON.stringify(body);
|
|
40
|
+
response.writeHead(status, {
|
|
41
|
+
...BASE_HEADERS,
|
|
42
|
+
"content-type": "application/json; charset=utf-8",
|
|
43
|
+
"content-length": String(Buffer.byteLength(text)),
|
|
44
|
+
...headers,
|
|
45
|
+
});
|
|
46
|
+
response.end(text);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function page(response: ServerResponse, status: number, html: string): void {
|
|
50
|
+
response.writeHead(status, {
|
|
51
|
+
...BASE_HEADERS,
|
|
52
|
+
"content-type": "text/html; charset=utf-8",
|
|
53
|
+
"content-security-policy":
|
|
54
|
+
"default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'",
|
|
55
|
+
"x-frame-options": "DENY",
|
|
56
|
+
// The device page posts its own form, whose `Origin` the server checks: under `no-referrer`
|
|
57
|
+
// browsers send `Origin: null` for a form's POST, so this page sends origins to itself only.
|
|
58
|
+
"referrer-policy": "same-origin",
|
|
59
|
+
});
|
|
60
|
+
response.end(html);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async function readBody(request: IncomingMessage, limit: number): Promise<Buffer | undefined> {
|
|
64
|
+
const chunks: Buffer[] = [];
|
|
65
|
+
let size = 0;
|
|
66
|
+
for await (const chunk of request) {
|
|
67
|
+
size += (chunk as Buffer).length;
|
|
68
|
+
if (size > limit) return undefined;
|
|
69
|
+
chunks.push(chunk as Buffer);
|
|
70
|
+
}
|
|
71
|
+
return Buffer.concat(chunks);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function escapeHtml(text: string): string {
|
|
75
|
+
return text.replace(/[&<>"']/g, (character) => `&#${character.charCodeAt(0)};`);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Options for {@link createApi}. */
|
|
79
|
+
export interface ApiOptions {
|
|
80
|
+
readonly config: RemoteServerConfig;
|
|
81
|
+
readonly auth: Authorization;
|
|
82
|
+
readonly log: Log;
|
|
83
|
+
readonly filesDir: string;
|
|
84
|
+
/** The hosted home an account's token names, opened on demand. */
|
|
85
|
+
readonly home: (homeId: string) => Promise<HostedHome>;
|
|
86
|
+
/** Notes a home was used, so it isn't closed while used. */
|
|
87
|
+
readonly touch: (homeId: string) => void;
|
|
88
|
+
/** How often an open binding's token and grant are checked; tests shorten it. */
|
|
89
|
+
readonly recheckMs?: number;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** The API origin's request and upgrade handlers. */
|
|
93
|
+
export interface Api {
|
|
94
|
+
request(request: IncomingMessage, response: ServerResponse, path: string): Promise<void>;
|
|
95
|
+
upgrade(request: IncomingMessage, socket: Duplex, head: Buffer, path: string): void;
|
|
96
|
+
close(): void;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** The development identity provider, when the configuration names one (§18.5, WP-29). */
|
|
100
|
+
function developmentProvider(
|
|
101
|
+
config: RemoteServerConfig,
|
|
102
|
+
): { id: string; label: string } | undefined {
|
|
103
|
+
const provider = config.identityProviders?.find((candidate) => candidate.kind === "development");
|
|
104
|
+
return provider ? { id: provider.id, label: provider.label ?? "Development sign-in" } : undefined;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** The device page: the code, the warning, and the development provider's sign-in. */
|
|
108
|
+
function devicePage(options: {
|
|
109
|
+
readonly code: string;
|
|
110
|
+
readonly provider: { id: string; label: string } | undefined;
|
|
111
|
+
readonly message?: string;
|
|
112
|
+
readonly done?: boolean;
|
|
113
|
+
}): string {
|
|
114
|
+
const body = options.done
|
|
115
|
+
? `<p>${escapeHtml(options.message ?? "Done.")}</p><p>You can close this page.</p>`
|
|
116
|
+
: `${options.message ? `<p role="alert">${escapeHtml(options.message)}</p>` : ""}
|
|
117
|
+
<p><strong>Approving links a machine to your account.</strong> That machine's Mostra can then host
|
|
118
|
+
pages under your account and receives their answers. Continue only if you started this sign-in
|
|
119
|
+
yourself, on that machine.</p>
|
|
120
|
+
${
|
|
121
|
+
options.provider
|
|
122
|
+
? `<form method="post" action="/device">
|
|
123
|
+
<label>Code <input name="user_code" value="${escapeHtml(options.code)}" autocomplete="off" required></label>
|
|
124
|
+
<p>${escapeHtml(options.provider.label)}: this server signs people in with a development provider,
|
|
125
|
+
which trusts the name you type. Use it only on a server you run for yourself or for tests.</p>
|
|
126
|
+
<label>Your name <input name="name" required maxlength="64"></label>
|
|
127
|
+
<input type="hidden" name="provider" value="${escapeHtml(options.provider.id)}">
|
|
128
|
+
<p><button name="decision" value="approve">Approve this machine</button>
|
|
129
|
+
<button name="decision" value="deny">Refuse</button></p>
|
|
130
|
+
</form>`
|
|
131
|
+
: "<p>This server has no identity provider configured, so nobody can sign in yet.</p>"
|
|
132
|
+
}`;
|
|
133
|
+
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="robots" content="noindex">
|
|
134
|
+
<meta name="viewport" content="width=device-width, initial-scale=1"><title>Link a machine to Mostra</title>
|
|
135
|
+
<style>body{font:16px/1.5 system-ui,sans-serif;max-width:34rem;margin:3rem auto;padding:0 1rem}
|
|
136
|
+
input{font:inherit;padding:.3rem}button{font:inherit;padding:.4rem .9rem;margin-right:.5rem}</style></head>
|
|
137
|
+
<body><h1>Link a machine to Mostra</h1>${body}</body></html>`;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Creates the API origin. */
|
|
141
|
+
export function createApi(options: ApiOptions): Api {
|
|
142
|
+
const { config, auth, log } = options;
|
|
143
|
+
const apiOrigin = config.apiOrigin;
|
|
144
|
+
const sockets = new WebSocketServer({
|
|
145
|
+
noServer: true,
|
|
146
|
+
maxPayload: MAX_FRAME_BYTES,
|
|
147
|
+
perMessageDeflate: false,
|
|
148
|
+
handleProtocols: (protocols) =>
|
|
149
|
+
protocols.has(BINDING_SUBPROTOCOL) ? BINDING_SUBPROTOCOL : false,
|
|
150
|
+
});
|
|
151
|
+
const bindings = new Set<WebSocket>();
|
|
152
|
+
|
|
153
|
+
const bearer = (request: IncomingMessage): Authenticated | undefined => {
|
|
154
|
+
const header = request.headers.authorization ?? "";
|
|
155
|
+
const match = /^bearer\s+(\S+)$/i.exec(header);
|
|
156
|
+
return match ? auth.authenticate(match[1] as string) : undefined;
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
const unauthorized = (response: ServerResponse, message: string): void =>
|
|
160
|
+
send(
|
|
161
|
+
response,
|
|
162
|
+
401,
|
|
163
|
+
{ code: "MOSTRA_REMOTE_LOGIN_FAILED", message },
|
|
164
|
+
{
|
|
165
|
+
"www-authenticate": `Bearer resource_metadata="${apiOrigin}/.well-known/oauth-protected-resource/host"`,
|
|
166
|
+
},
|
|
167
|
+
);
|
|
168
|
+
|
|
169
|
+
const metadata = () => ({
|
|
170
|
+
issuer: apiOrigin,
|
|
171
|
+
token_endpoint: `${apiOrigin}/oauth/token`,
|
|
172
|
+
device_authorization_endpoint: `${apiOrigin}/oauth/device`,
|
|
173
|
+
revocation_endpoint: `${apiOrigin}/oauth/revoke`,
|
|
174
|
+
grant_types_supported: ["urn:ietf:params:oauth:grant-type:device_code", "refresh_token"],
|
|
175
|
+
token_endpoint_auth_methods_supported: ["none"],
|
|
176
|
+
code_challenge_methods_supported: ["S256"],
|
|
177
|
+
scopes_supported: ["mostra", "offline_access"],
|
|
178
|
+
authorization_response_iss_parameter_supported: true,
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
const form = async (request: IncomingMessage): Promise<URLSearchParams | undefined> => {
|
|
182
|
+
const type = request.headers["content-type"] ?? "";
|
|
183
|
+
if (!type.startsWith("application/x-www-form-urlencoded")) return undefined;
|
|
184
|
+
const body = await readBody(request, 64 * 1024);
|
|
185
|
+
return body === undefined ? undefined : new URLSearchParams(body.toString("utf8"));
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
const upload = async (
|
|
189
|
+
request: IncomingMessage,
|
|
190
|
+
response: ServerResponse,
|
|
191
|
+
sha: string,
|
|
192
|
+
): Promise<void> => {
|
|
193
|
+
const who = bearer(request);
|
|
194
|
+
if (!who) {
|
|
195
|
+
unauthorized(response, "Version files need the binding's access token.");
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
const home = await options.home(who.homeId);
|
|
199
|
+
options.touch(who.homeId);
|
|
200
|
+
// A file is accepted only for a pending push of this home that names it as missing, so no
|
|
201
|
+
// home stores bytes nobody asked for, nor learns what another home holds (§18.2).
|
|
202
|
+
if (!home.wanted(sha)) {
|
|
203
|
+
send(response, 409, {
|
|
204
|
+
code: "MOSTRA_HOME_INTEGRITY",
|
|
205
|
+
message: "No pending push of this home names that file as missing.",
|
|
206
|
+
});
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
const target = join(options.filesDir, sha);
|
|
210
|
+
const scratch = join(options.filesDir, `.upload-${randomBytes(8).toString("hex")}`);
|
|
211
|
+
const hash = createHash("sha256");
|
|
212
|
+
let size = 0;
|
|
213
|
+
let tooLarge = false;
|
|
214
|
+
await new Promise<void>((resolve, reject) => {
|
|
215
|
+
const out = createWriteStream(scratch, { mode: 0o600 });
|
|
216
|
+
request.on("data", (chunk: Buffer) => {
|
|
217
|
+
size += chunk.length;
|
|
218
|
+
if (size > MAX_FILE_BYTES) {
|
|
219
|
+
tooLarge = true;
|
|
220
|
+
request.destroy();
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
hash.update(chunk);
|
|
224
|
+
out.write(chunk);
|
|
225
|
+
});
|
|
226
|
+
request.on("end", () => out.end(() => resolve()));
|
|
227
|
+
request.on("error", reject);
|
|
228
|
+
request.on("close", () => {
|
|
229
|
+
if (tooLarge) out.end(() => resolve());
|
|
230
|
+
});
|
|
231
|
+
}).catch(() => undefined);
|
|
232
|
+
if (tooLarge || hash.digest("hex") !== sha) {
|
|
233
|
+
await rm(scratch, { force: true });
|
|
234
|
+
send(response, tooLarge ? 413 : 400, {
|
|
235
|
+
code: "MOSTRA_HOME_INTEGRITY",
|
|
236
|
+
message: tooLarge ? "The file is too large." : "The bytes don't hash to the file's name.",
|
|
237
|
+
});
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
if (existsSync(target)) await rm(scratch, { force: true });
|
|
241
|
+
else renameSync(scratch, target);
|
|
242
|
+
home.uploaded(sha);
|
|
243
|
+
send(response, 201, { sha256: sha, size });
|
|
244
|
+
};
|
|
245
|
+
|
|
246
|
+
return {
|
|
247
|
+
async request(request, response, path) {
|
|
248
|
+
const method = request.method ?? "GET";
|
|
249
|
+
if (method === "GET" && path === "/.well-known/oauth-authorization-server") {
|
|
250
|
+
send(response, 200, metadata());
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
if (method === "GET" && path === "/.well-known/oauth-protected-resource/host") {
|
|
254
|
+
send(response, 200, {
|
|
255
|
+
resource: `${apiOrigin}/host`,
|
|
256
|
+
authorization_servers: [apiOrigin],
|
|
257
|
+
scopes_supported: ["mostra"],
|
|
258
|
+
});
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
if (method === "POST" && path === "/oauth/device") {
|
|
262
|
+
const body = await form(request);
|
|
263
|
+
if (!body) {
|
|
264
|
+
send(response, 400, { error: "invalid_request", error_description: "Send a form." });
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
const answer = auth.device(body);
|
|
268
|
+
if ("error" in answer && typeof answer["status"] === "number") {
|
|
269
|
+
const failed = answer as unknown as {
|
|
270
|
+
status: number;
|
|
271
|
+
error: string;
|
|
272
|
+
description: string;
|
|
273
|
+
};
|
|
274
|
+
send(response, failed.status, {
|
|
275
|
+
error: failed.error,
|
|
276
|
+
error_description: failed.description,
|
|
277
|
+
});
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
send(response, 200, answer);
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
if (method === "POST" && path === "/oauth/token") {
|
|
284
|
+
const body = await form(request);
|
|
285
|
+
if (!body) {
|
|
286
|
+
send(response, 400, { error: "invalid_request", error_description: "Send a form." });
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
const answer = auth.token(body);
|
|
290
|
+
if ("error" in answer) {
|
|
291
|
+
send(response, answer.status, {
|
|
292
|
+
error: answer.error,
|
|
293
|
+
error_description: answer.description,
|
|
294
|
+
});
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
send(response, 200, answer);
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
if (method === "POST" && path === "/oauth/revoke") {
|
|
301
|
+
const body = await form(request);
|
|
302
|
+
if (body) auth.revoke(body);
|
|
303
|
+
send(response, 200, {});
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
if (path === "/device") {
|
|
307
|
+
const provider = developmentProvider(config);
|
|
308
|
+
if (method === "GET") {
|
|
309
|
+
const code = new URL(request.url ?? "/", apiOrigin).searchParams.get("user_code") ?? "";
|
|
310
|
+
page(response, 200, devicePage({ code, provider }));
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
if (method === "POST") {
|
|
314
|
+
// The page's own form only: a cross-site form post approves nothing.
|
|
315
|
+
if (request.headers.origin !== apiOrigin) {
|
|
316
|
+
page(
|
|
317
|
+
response,
|
|
318
|
+
403,
|
|
319
|
+
devicePage({ code: "", provider, message: "This form must be sent from this page." }),
|
|
320
|
+
);
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
const body = await form(request);
|
|
324
|
+
const code = body?.get("user_code") ?? "";
|
|
325
|
+
const name = (body?.get("name") ?? "").trim().slice(0, 64);
|
|
326
|
+
if (!body || !provider || body.get("provider") !== provider.id || name === "") {
|
|
327
|
+
page(
|
|
328
|
+
response,
|
|
329
|
+
400,
|
|
330
|
+
devicePage({ code, provider, message: "Enter the code and your name." }),
|
|
331
|
+
);
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
const approve = body.get("decision") === "approve";
|
|
335
|
+
const decided = auth.decide({
|
|
336
|
+
code,
|
|
337
|
+
approve,
|
|
338
|
+
identity: { provider: provider.id, subject: name.toLowerCase(), name },
|
|
339
|
+
});
|
|
340
|
+
if (!decided.ok) {
|
|
341
|
+
page(response, 400, devicePage({ code, provider, message: decided.reason }));
|
|
342
|
+
return;
|
|
343
|
+
}
|
|
344
|
+
page(
|
|
345
|
+
response,
|
|
346
|
+
200,
|
|
347
|
+
devicePage({
|
|
348
|
+
code,
|
|
349
|
+
provider,
|
|
350
|
+
done: true,
|
|
351
|
+
message: approve
|
|
352
|
+
? "The machine is linked to your account."
|
|
353
|
+
: "The sign-in was refused.",
|
|
354
|
+
}),
|
|
355
|
+
);
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
const file = /^\/files\/([0-9a-f]{64})$/.exec(path);
|
|
360
|
+
if (file && method === "PUT") {
|
|
361
|
+
await upload(request, response, file[1] as string);
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
send(response, 404, {
|
|
365
|
+
code: "MOSTRA_HYGIENE_NOT_SERVED",
|
|
366
|
+
message: "Nothing is served at this path.",
|
|
367
|
+
});
|
|
368
|
+
},
|
|
369
|
+
|
|
370
|
+
upgrade(request, socket, head, path) {
|
|
371
|
+
const refuse = (status: number, text: string, extra = ""): void => {
|
|
372
|
+
socket.end(
|
|
373
|
+
`HTTP/1.1 ${status} ${text}\r\nconnection: close\r\ncontent-length: 0\r\n${extra}\r\n`,
|
|
374
|
+
);
|
|
375
|
+
};
|
|
376
|
+
if (path !== "/host") {
|
|
377
|
+
refuse(404, "Not Found");
|
|
378
|
+
return;
|
|
379
|
+
}
|
|
380
|
+
const who = bearer(request);
|
|
381
|
+
if (!who) {
|
|
382
|
+
refuse(
|
|
383
|
+
401,
|
|
384
|
+
"Unauthorized",
|
|
385
|
+
`www-authenticate: Bearer resource_metadata="${apiOrigin}/.well-known/oauth-protected-resource/host"\r\n`,
|
|
386
|
+
);
|
|
387
|
+
return;
|
|
388
|
+
}
|
|
389
|
+
void options.home(who.homeId).then(
|
|
390
|
+
(home) => {
|
|
391
|
+
sockets.handleUpgrade(request, socket, head, (ws) => {
|
|
392
|
+
bindings.add(ws);
|
|
393
|
+
let expiresAt = who.expiresAt;
|
|
394
|
+
const attributes = {
|
|
395
|
+
accountId: who.accountId,
|
|
396
|
+
grantId: who.grantId,
|
|
397
|
+
homeId: who.homeId,
|
|
398
|
+
linkId: who.linkId,
|
|
399
|
+
replaceToken: (next: number) => {
|
|
400
|
+
expiresAt = next;
|
|
401
|
+
},
|
|
402
|
+
};
|
|
403
|
+
// The binding ends at its token's expiry unless refreshed in band (`remote/token`), and
|
|
404
|
+
// within 60 s of the grant's revocation or the account's suspension (§18.2).
|
|
405
|
+
const watch = setInterval(
|
|
406
|
+
() => {
|
|
407
|
+
if (Date.now() >= expiresAt) {
|
|
408
|
+
log.info("binding.token_expired", { home: who.homeId });
|
|
409
|
+
ws.close(4401, "token expired");
|
|
410
|
+
} else if (!auth.grantLive(who.grantId)) {
|
|
411
|
+
log.info("binding.grant_revoked", { home: who.homeId });
|
|
412
|
+
ws.close(4403, "grant revoked");
|
|
413
|
+
}
|
|
414
|
+
},
|
|
415
|
+
Math.min(GRANT_RECHECK_MS, options.recheckMs ?? GRANT_RECHECK_MS),
|
|
416
|
+
);
|
|
417
|
+
watch.unref();
|
|
418
|
+
ws.once("close", () => {
|
|
419
|
+
clearInterval(watch);
|
|
420
|
+
bindings.delete(ws);
|
|
421
|
+
});
|
|
422
|
+
ws.on("message", () => options.touch(who.homeId));
|
|
423
|
+
serveWebSocket(home.protocol, ws, { attributes, log });
|
|
424
|
+
log.info("binding.opened", { home: who.homeId, link: who.linkId });
|
|
425
|
+
});
|
|
426
|
+
},
|
|
427
|
+
(error: unknown) => {
|
|
428
|
+
log.error("binding.home_failed", { home: who.homeId, error });
|
|
429
|
+
refuse(503, "Service Unavailable");
|
|
430
|
+
},
|
|
431
|
+
);
|
|
432
|
+
},
|
|
433
|
+
|
|
434
|
+
close() {
|
|
435
|
+
for (const ws of bindings) ws.terminate();
|
|
436
|
+
sockets.close();
|
|
437
|
+
},
|
|
438
|
+
};
|
|
439
|
+
}
|