@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
|
@@ -0,0 +1,613 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The remote server's authorization server, as far as WP-29 builds it (INTERFACES §18.5, D165
|
|
3
|
+
* items 2, 8): the OAuth 2.0 device authorization grant (RFC 8628) behind `mostra login`, with
|
|
4
|
+
* rotating refresh tokens and revocation, and a development identity provider for tests and a
|
|
5
|
+
* self-hoster's first run. WP-30 adds the real identity providers, viewer sign-in and the MCP
|
|
6
|
+
* clients' flows on the same tables.
|
|
7
|
+
*
|
|
8
|
+
* Every token is an opaque random secret, stored only as its SHA-256 (DATA_MODEL §7.1): a copy of
|
|
9
|
+
* the directory grants nothing. Access tokens last an hour; a refresh token rotates on every use,
|
|
10
|
+
* returns the same successor for 30 s after it was used, so parallel refreshes don't collide, and a
|
|
11
|
+
* use after that revokes its grant. The device page says that approving links a machine to the
|
|
12
|
+
* account, and a new link is the hosted event `instance.linked`.
|
|
13
|
+
*/
|
|
14
|
+
import { createHash, randomBytes, randomInt, timingSafeEqual } from "node:crypto";
|
|
15
|
+
import { AccountId, HomeId, LinkId } from "@mostra/protocol";
|
|
16
|
+
import type { Ledger, LedgerDb } from "../ledger/index.ts";
|
|
17
|
+
import type { Log } from "../log.ts";
|
|
18
|
+
import type { RemoteServerConfig } from "./config.ts";
|
|
19
|
+
|
|
20
|
+
/** The CLI's client ID: a first-party public client (§18.5). */
|
|
21
|
+
export const CLI_CLIENT_ID = "mostra-cli";
|
|
22
|
+
|
|
23
|
+
/** The device grant's type (RFC 8628 §3.4). */
|
|
24
|
+
export const DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
|
|
25
|
+
|
|
26
|
+
const ACCESS_TTL_MS = 60 * 60 * 1000;
|
|
27
|
+
const REFRESH_TTL_MS = 90 * 24 * 60 * 60 * 1000;
|
|
28
|
+
const DEVICE_TTL_MS = 10 * 60 * 1000;
|
|
29
|
+
const DEVICE_INTERVAL_S = 5;
|
|
30
|
+
const ROTATION_GRACE_MS = 30_000;
|
|
31
|
+
|
|
32
|
+
/** User codes: eight letters a person can't confuse (RFC 8628 §6.1), shown as `ABCD-EFGH`. */
|
|
33
|
+
const USER_CODE_LETTERS = "BCDFGHJKLMNPQRSTVWXZ";
|
|
34
|
+
|
|
35
|
+
/** What a valid access token names. */
|
|
36
|
+
export interface Authenticated {
|
|
37
|
+
readonly accountId: string;
|
|
38
|
+
readonly accountName: string | undefined;
|
|
39
|
+
readonly grantId: string;
|
|
40
|
+
readonly homeId: string;
|
|
41
|
+
readonly linkId: string | undefined;
|
|
42
|
+
readonly expiresAt: number;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** An OAuth error answer (RFC 6749 §5.2, RFC 8628 §3.5). */
|
|
46
|
+
export interface OAuthError {
|
|
47
|
+
readonly status: number;
|
|
48
|
+
readonly error: string;
|
|
49
|
+
readonly description: string;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The token endpoint's success answer. */
|
|
53
|
+
export interface TokenAnswer {
|
|
54
|
+
readonly access_token: string;
|
|
55
|
+
readonly token_type: "Bearer";
|
|
56
|
+
readonly expires_in: number;
|
|
57
|
+
readonly refresh_token: string;
|
|
58
|
+
readonly scope: string;
|
|
59
|
+
readonly mostra_account: { readonly id: string; readonly name?: string };
|
|
60
|
+
readonly mostra_instance: string;
|
|
61
|
+
/** Whether this instance is the account's default instance (D165 item 1b). */
|
|
62
|
+
readonly mostra_default: boolean;
|
|
63
|
+
/** The account's hosted home. */
|
|
64
|
+
readonly mostra_home: string;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** The SHA-256 of a secret, as the directory stores it. */
|
|
68
|
+
export function hashSecret(secret: string): string {
|
|
69
|
+
return createHash("sha256").update(secret).digest("hex");
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function secret(): string {
|
|
73
|
+
return randomBytes(32).toString("base64url");
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function userCode(): string {
|
|
77
|
+
let code = "";
|
|
78
|
+
for (let index = 0; index < 8; index++)
|
|
79
|
+
code += USER_CODE_LETTERS[randomInt(USER_CODE_LETTERS.length)];
|
|
80
|
+
return code;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** `abcd-efgh`, `ABCDEFGH` → `ABCDEFGH`. */
|
|
84
|
+
function normalizeUserCode(input: string): string {
|
|
85
|
+
return input.toUpperCase().replace(/[^A-Z]/g, "");
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** The device grant's state, kept in its `token` row's `data_json`. */
|
|
89
|
+
interface DeviceState {
|
|
90
|
+
readonly userCode: string;
|
|
91
|
+
readonly status: "pending" | "approved" | "denied";
|
|
92
|
+
readonly accountId?: string;
|
|
93
|
+
readonly instance?: string;
|
|
94
|
+
readonly name?: string;
|
|
95
|
+
readonly lastPollAt?: number;
|
|
96
|
+
/** The instance asked to become the account's default (`mostra login --default`). */
|
|
97
|
+
readonly makeDefault?: boolean;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Options for {@link createAuthorization}. */
|
|
101
|
+
export interface AuthorizationOptions {
|
|
102
|
+
readonly directory: Ledger;
|
|
103
|
+
readonly config: RemoteServerConfig;
|
|
104
|
+
readonly log: Log;
|
|
105
|
+
readonly now?: () => number;
|
|
106
|
+
/** How long an access token lasts; an hour unless tests shorten it. */
|
|
107
|
+
readonly accessTtlMs?: number;
|
|
108
|
+
/**
|
|
109
|
+
* Called when an instance link was made or bound again (`instance.linked`, §18.5): the server
|
|
110
|
+
* appends the event in the hosted home.
|
|
111
|
+
*/
|
|
112
|
+
readonly linked?: (event: {
|
|
113
|
+
readonly homeId: string;
|
|
114
|
+
readonly linkId: string;
|
|
115
|
+
readonly name: string;
|
|
116
|
+
}) => void;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** The authorization server. */
|
|
120
|
+
export interface Authorization {
|
|
121
|
+
/** `POST /oauth/device`. */
|
|
122
|
+
device(form: URLSearchParams): Record<string, unknown> | OAuthError;
|
|
123
|
+
/** `POST /oauth/token`. */
|
|
124
|
+
token(form: URLSearchParams): TokenAnswer | OAuthError;
|
|
125
|
+
/** `POST /oauth/revoke` (RFC 7009): revokes the grant a token belongs to. */
|
|
126
|
+
revoke(form: URLSearchParams): void;
|
|
127
|
+
/** What a bearer token names, or `undefined` when it is unknown, expired or revoked. */
|
|
128
|
+
authenticate(bearer: string): Authenticated | undefined;
|
|
129
|
+
/** Whether a grant is still live (not revoked, its account active). */
|
|
130
|
+
grantLive(grantId: string): boolean;
|
|
131
|
+
/** The device page's state for a user code: pending, or why it can't be approved. */
|
|
132
|
+
pendingCode(
|
|
133
|
+
code: string,
|
|
134
|
+
): { readonly ok: true } | { readonly ok: false; readonly reason: string };
|
|
135
|
+
/**
|
|
136
|
+
* Approves or denies a device code as `person` (the development provider's name, or WP-30's
|
|
137
|
+
* signed-in identity), recording the account's consent for the CLI.
|
|
138
|
+
*/
|
|
139
|
+
decide(input: {
|
|
140
|
+
readonly code: string;
|
|
141
|
+
readonly approve: boolean;
|
|
142
|
+
readonly identity: {
|
|
143
|
+
readonly provider: string;
|
|
144
|
+
readonly subject: string;
|
|
145
|
+
readonly name?: string;
|
|
146
|
+
};
|
|
147
|
+
}): { readonly ok: true } | { readonly ok: false; readonly reason: string };
|
|
148
|
+
/** The verification address people open. */
|
|
149
|
+
readonly verificationUri: string;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function oauthError(status: number, error: string, description: string): OAuthError {
|
|
153
|
+
return { status, error, description };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Creates the authorization server over the server's directory. */
|
|
157
|
+
export function createAuthorization(options: AuthorizationOptions): Authorization {
|
|
158
|
+
const { directory, config, log } = options;
|
|
159
|
+
const now = options.now ?? (() => Date.now());
|
|
160
|
+
const accessTtlMs = options.accessTtlMs ?? ACCESS_TTL_MS;
|
|
161
|
+
const iso = (ms: number): string => new Date(ms).toISOString();
|
|
162
|
+
const verificationUri = `${config.apiOrigin}/device`;
|
|
163
|
+
|
|
164
|
+
directory.write((db) => {
|
|
165
|
+
db.run(
|
|
166
|
+
"INSERT OR IGNORE INTO oauth_client (id, kind, metadata_json, created_at) VALUES (?, 'cli', ?, ?)",
|
|
167
|
+
CLI_CLIENT_ID,
|
|
168
|
+
JSON.stringify({ client_name: "Mostra CLI" }),
|
|
169
|
+
iso(now()),
|
|
170
|
+
);
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
const deviceRow = (db: LedgerDb, hash: string) =>
|
|
174
|
+
db.get<{ data_json: string; expires_at: string }>(
|
|
175
|
+
"SELECT data_json, expires_at FROM token WHERE hash = ? AND kind = 'device'",
|
|
176
|
+
hash,
|
|
177
|
+
);
|
|
178
|
+
|
|
179
|
+
/** The account for a sign-in identity, made on the first sign-in. */
|
|
180
|
+
const accountFor = (
|
|
181
|
+
db: LedgerDb,
|
|
182
|
+
identity: { provider: string; subject: string; name?: string },
|
|
183
|
+
): string => {
|
|
184
|
+
const found = db.get<{ account_id: string }>(
|
|
185
|
+
"SELECT account_id FROM identity WHERE provider = ? AND subject = ?",
|
|
186
|
+
identity.provider,
|
|
187
|
+
identity.subject,
|
|
188
|
+
);
|
|
189
|
+
if (found) return found.account_id;
|
|
190
|
+
const account = AccountId.create();
|
|
191
|
+
db.run(
|
|
192
|
+
"INSERT INTO account (id, name, status, created_at) VALUES (?, ?, 'active', ?)",
|
|
193
|
+
account,
|
|
194
|
+
identity.name ?? null,
|
|
195
|
+
iso(now()),
|
|
196
|
+
);
|
|
197
|
+
db.run(
|
|
198
|
+
"INSERT INTO identity (provider, subject, account_id, name, linked_at) VALUES (?, ?, ?, ?, ?)",
|
|
199
|
+
identity.provider,
|
|
200
|
+
identity.subject,
|
|
201
|
+
account,
|
|
202
|
+
identity.name ?? null,
|
|
203
|
+
iso(now()),
|
|
204
|
+
);
|
|
205
|
+
return account;
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
/** The account's hosted home, made on its first link (one home per owner per server). */
|
|
209
|
+
const homeFor = (db: LedgerDb, account: string): string => {
|
|
210
|
+
const found = db.get<{ id: string }>("SELECT id FROM home WHERE owner_account_id = ?", account);
|
|
211
|
+
if (found) return found.id;
|
|
212
|
+
const home = HomeId.create();
|
|
213
|
+
db.run(
|
|
214
|
+
"INSERT INTO home (id, owner_account_id, data_path, created_at) VALUES (?, ?, ?, ?)",
|
|
215
|
+
home,
|
|
216
|
+
account,
|
|
217
|
+
`homes/${home}`,
|
|
218
|
+
iso(now()),
|
|
219
|
+
);
|
|
220
|
+
return home;
|
|
221
|
+
};
|
|
222
|
+
|
|
223
|
+
/** Makes or binds again the instance link a sign-in names. */
|
|
224
|
+
const linkFor = (
|
|
225
|
+
db: LedgerDb,
|
|
226
|
+
account: string,
|
|
227
|
+
home: string,
|
|
228
|
+
wanted: string | undefined,
|
|
229
|
+
name: string,
|
|
230
|
+
): string => {
|
|
231
|
+
if (wanted !== undefined && LinkId.is(wanted)) {
|
|
232
|
+
const row = db.get<{ account_id: string }>(
|
|
233
|
+
"SELECT account_id FROM instance_link WHERE id = ?",
|
|
234
|
+
wanted,
|
|
235
|
+
);
|
|
236
|
+
// A link is rebound only for its own account: another account's ID names nothing here.
|
|
237
|
+
if (row?.account_id === account) {
|
|
238
|
+
db.run("UPDATE instance_link SET revoked_at = NULL, name = ? WHERE id = ?", name, wanted);
|
|
239
|
+
return wanted;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
const link = LinkId.create();
|
|
243
|
+
const first =
|
|
244
|
+
db.get<{ n: number }>("SELECT COUNT(*) AS n FROM instance_link WHERE account_id = ?", account)
|
|
245
|
+
?.n === 0;
|
|
246
|
+
db.run(
|
|
247
|
+
"INSERT INTO instance_link (id, account_id, home_id, name, is_default, relay_high, linked_at) VALUES (?, ?, ?, ?, ?, 0, ?)",
|
|
248
|
+
link,
|
|
249
|
+
account,
|
|
250
|
+
home,
|
|
251
|
+
name,
|
|
252
|
+
first ? 1 : 0,
|
|
253
|
+
iso(now()),
|
|
254
|
+
);
|
|
255
|
+
return link;
|
|
256
|
+
};
|
|
257
|
+
|
|
258
|
+
/** Issues an access and a refresh token for a grant. */
|
|
259
|
+
const issue = (db: LedgerDb, grantId: string): { access: string; refresh: string } => {
|
|
260
|
+
const access = secret();
|
|
261
|
+
const refresh = secret();
|
|
262
|
+
db.run(
|
|
263
|
+
"INSERT INTO token (hash, grant_id, kind, expires_at) VALUES (?, ?, 'access', ?)",
|
|
264
|
+
hashSecret(access),
|
|
265
|
+
grantId,
|
|
266
|
+
iso(now() + accessTtlMs),
|
|
267
|
+
);
|
|
268
|
+
db.run(
|
|
269
|
+
"INSERT INTO token (hash, grant_id, kind, expires_at) VALUES (?, ?, 'refresh', ?)",
|
|
270
|
+
hashSecret(refresh),
|
|
271
|
+
grantId,
|
|
272
|
+
iso(now() + REFRESH_TTL_MS),
|
|
273
|
+
);
|
|
274
|
+
return { access, refresh };
|
|
275
|
+
};
|
|
276
|
+
|
|
277
|
+
const answer = (
|
|
278
|
+
db: LedgerDb,
|
|
279
|
+
grantId: string,
|
|
280
|
+
tokens: { access: string; refresh: string },
|
|
281
|
+
): TokenAnswer => {
|
|
282
|
+
const row = db.get<{
|
|
283
|
+
account_id: string;
|
|
284
|
+
link_id: string | null;
|
|
285
|
+
name: string | null;
|
|
286
|
+
is_default: number | null;
|
|
287
|
+
home_id: string | null;
|
|
288
|
+
}>(
|
|
289
|
+
`SELECT g.account_id, g.link_id, a.name, l.is_default, l.home_id
|
|
290
|
+
FROM "grant" g JOIN account a ON a.id = g.account_id
|
|
291
|
+
LEFT JOIN instance_link l ON l.id = g.link_id WHERE g.id = ?`,
|
|
292
|
+
grantId,
|
|
293
|
+
);
|
|
294
|
+
if (!row) throw new Error("grant vanished");
|
|
295
|
+
return {
|
|
296
|
+
access_token: tokens.access,
|
|
297
|
+
token_type: "Bearer",
|
|
298
|
+
expires_in: Math.max(1, Math.floor(accessTtlMs / 1000)),
|
|
299
|
+
refresh_token: tokens.refresh,
|
|
300
|
+
scope: "mostra",
|
|
301
|
+
mostra_account: { id: row.account_id, ...(row.name !== null ? { name: row.name } : {}) },
|
|
302
|
+
mostra_instance: row.link_id ?? "",
|
|
303
|
+
mostra_default: row.is_default === 1,
|
|
304
|
+
mostra_home: row.home_id ?? "",
|
|
305
|
+
};
|
|
306
|
+
};
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* The successors of refresh tokens used in the last 30 s, by the used token's hash: kept in
|
|
310
|
+
* memory only, so the directory never holds a usable secret. After a restart inside the grace, a
|
|
311
|
+
* repeated refresh is refused without revoking anything; the client still holds its successor.
|
|
312
|
+
*/
|
|
313
|
+
const recent = new Map<
|
|
314
|
+
string,
|
|
315
|
+
{ readonly tokens: { access: string; refresh: string }; readonly at: number }
|
|
316
|
+
>();
|
|
317
|
+
const forgetOld = (): void => {
|
|
318
|
+
for (const [hash, entry] of recent)
|
|
319
|
+
if (now() - entry.at > ROTATION_GRACE_MS) recent.delete(hash);
|
|
320
|
+
};
|
|
321
|
+
|
|
322
|
+
const grantLiveIn = (db: LedgerDb, grantId: string): boolean => {
|
|
323
|
+
const row = db.get<{ revoked_at: string | null; status: string }>(
|
|
324
|
+
'SELECT g.revoked_at, a.status FROM "grant" g JOIN account a ON a.id = g.account_id WHERE g.id = ?',
|
|
325
|
+
grantId,
|
|
326
|
+
);
|
|
327
|
+
return row !== undefined && row.revoked_at === null && row.status === "active";
|
|
328
|
+
};
|
|
329
|
+
|
|
330
|
+
return {
|
|
331
|
+
verificationUri,
|
|
332
|
+
|
|
333
|
+
device(form) {
|
|
334
|
+
if (form.get("client_id") !== CLI_CLIENT_ID) {
|
|
335
|
+
return oauthError(401, "invalid_client", "Only the Mostra CLI uses the device grant here.");
|
|
336
|
+
}
|
|
337
|
+
const scope = form.get("scope") ?? "mostra";
|
|
338
|
+
if (!scope.split(" ").every((part) => part === "mostra" || part === "offline_access")) {
|
|
339
|
+
return oauthError(400, "invalid_scope", "The only scope is mostra.");
|
|
340
|
+
}
|
|
341
|
+
const deviceCode = secret();
|
|
342
|
+
const code = userCode();
|
|
343
|
+
const instance = form.get("mostra_instance") ?? undefined;
|
|
344
|
+
const name = (form.get("mostra_name") ?? "").slice(0, 128) || "Mostra instance";
|
|
345
|
+
const state: DeviceState = {
|
|
346
|
+
userCode: code,
|
|
347
|
+
status: "pending",
|
|
348
|
+
name,
|
|
349
|
+
...(instance !== undefined ? { instance } : {}),
|
|
350
|
+
...(form.get("mostra_default") === "1" ? { makeDefault: true } : {}),
|
|
351
|
+
};
|
|
352
|
+
directory.write((db) =>
|
|
353
|
+
db.run(
|
|
354
|
+
"INSERT INTO token (hash, kind, expires_at, data_json) VALUES (?, 'device', ?, ?)",
|
|
355
|
+
hashSecret(deviceCode),
|
|
356
|
+
iso(now() + DEVICE_TTL_MS),
|
|
357
|
+
JSON.stringify(state),
|
|
358
|
+
),
|
|
359
|
+
);
|
|
360
|
+
const shown = `${code.slice(0, 4)}-${code.slice(4)}`;
|
|
361
|
+
log.info("auth.device_started", {});
|
|
362
|
+
return {
|
|
363
|
+
device_code: deviceCode,
|
|
364
|
+
user_code: shown,
|
|
365
|
+
verification_uri: verificationUri,
|
|
366
|
+
verification_uri_complete: `${verificationUri}?user_code=${shown}`,
|
|
367
|
+
expires_in: Math.floor(DEVICE_TTL_MS / 1000),
|
|
368
|
+
interval: DEVICE_INTERVAL_S,
|
|
369
|
+
};
|
|
370
|
+
},
|
|
371
|
+
|
|
372
|
+
token(form) {
|
|
373
|
+
const grantType = form.get("grant_type");
|
|
374
|
+
if (form.get("client_id") !== CLI_CLIENT_ID) {
|
|
375
|
+
return oauthError(401, "invalid_client", "Unknown client.");
|
|
376
|
+
}
|
|
377
|
+
if (grantType === DEVICE_GRANT) {
|
|
378
|
+
const deviceCode = form.get("device_code") ?? "";
|
|
379
|
+
const hash = hashSecret(deviceCode);
|
|
380
|
+
return directory.write((db): TokenAnswer | OAuthError => {
|
|
381
|
+
const row = deviceRow(db, hash);
|
|
382
|
+
if (!row) return oauthError(400, "invalid_grant", "Unknown device code.");
|
|
383
|
+
if (Date.parse(row.expires_at) <= now()) {
|
|
384
|
+
return oauthError(400, "expired_token", "The code expired; sign in again.");
|
|
385
|
+
}
|
|
386
|
+
const state = JSON.parse(row.data_json) as DeviceState;
|
|
387
|
+
if (state.status === "denied") {
|
|
388
|
+
return oauthError(400, "access_denied", "The sign-in was refused.");
|
|
389
|
+
}
|
|
390
|
+
if (state.status === "pending") {
|
|
391
|
+
const tooSoon =
|
|
392
|
+
state.lastPollAt !== undefined &&
|
|
393
|
+
now() - state.lastPollAt < DEVICE_INTERVAL_S * 1000 - 250;
|
|
394
|
+
db.run(
|
|
395
|
+
"UPDATE token SET data_json = ? WHERE hash = ?",
|
|
396
|
+
JSON.stringify({ ...state, lastPollAt: now() }),
|
|
397
|
+
hash,
|
|
398
|
+
);
|
|
399
|
+
return tooSoon
|
|
400
|
+
? oauthError(400, "slow_down", "Poll less often.")
|
|
401
|
+
: oauthError(400, "authorization_pending", "Waiting for the person to approve.");
|
|
402
|
+
}
|
|
403
|
+
// Approved: one grant, once. The device code is spent here.
|
|
404
|
+
const account = state.accountId as string;
|
|
405
|
+
const home = homeFor(db, account);
|
|
406
|
+
const link = linkFor(db, account, home, state.instance, state.name ?? "Mostra instance");
|
|
407
|
+
// `mostra login --default` makes this instance the account's default (D165 item 1b):
|
|
408
|
+
// chat-host authoring goes to it. One default per account (a unique index).
|
|
409
|
+
if (state.makeDefault === true) {
|
|
410
|
+
db.run(
|
|
411
|
+
"UPDATE instance_link SET is_default = 0 WHERE account_id = ? AND id != ?",
|
|
412
|
+
account,
|
|
413
|
+
link,
|
|
414
|
+
);
|
|
415
|
+
db.run("UPDATE instance_link SET is_default = 1 WHERE id = ?", link);
|
|
416
|
+
}
|
|
417
|
+
const grantId = `grt_${randomBytes(16).toString("hex")}`;
|
|
418
|
+
db.run(
|
|
419
|
+
'INSERT INTO "grant" (id, account_id, client_id, scope, resource, link_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)',
|
|
420
|
+
grantId,
|
|
421
|
+
account,
|
|
422
|
+
CLI_CLIENT_ID,
|
|
423
|
+
"mostra",
|
|
424
|
+
`${config.apiOrigin}/host`,
|
|
425
|
+
link,
|
|
426
|
+
iso(now()),
|
|
427
|
+
);
|
|
428
|
+
db.run("DELETE FROM token WHERE hash = ?", hash);
|
|
429
|
+
const tokens = issue(db, grantId);
|
|
430
|
+
setImmediate(() =>
|
|
431
|
+
options.linked?.({ homeId: home, linkId: link, name: state.name ?? "" }),
|
|
432
|
+
);
|
|
433
|
+
log.info("auth.linked", { account, home, link });
|
|
434
|
+
return answer(db, grantId, tokens);
|
|
435
|
+
});
|
|
436
|
+
}
|
|
437
|
+
if (grantType === "refresh_token") {
|
|
438
|
+
const presented = form.get("refresh_token") ?? "";
|
|
439
|
+
const hash = hashSecret(presented);
|
|
440
|
+
return directory.write((db): TokenAnswer | OAuthError => {
|
|
441
|
+
const row = db.get<{
|
|
442
|
+
grant_id: string;
|
|
443
|
+
expires_at: string;
|
|
444
|
+
used_at: string | null;
|
|
445
|
+
}>(
|
|
446
|
+
"SELECT grant_id, expires_at, used_at FROM token WHERE hash = ? AND kind = 'refresh'",
|
|
447
|
+
hash,
|
|
448
|
+
);
|
|
449
|
+
if (!row || !grantLiveIn(db, row.grant_id)) {
|
|
450
|
+
return oauthError(
|
|
451
|
+
400,
|
|
452
|
+
"invalid_grant",
|
|
453
|
+
"The refresh token isn't valid; sign in again.",
|
|
454
|
+
);
|
|
455
|
+
}
|
|
456
|
+
if (Date.parse(row.expires_at) <= now()) {
|
|
457
|
+
return oauthError(400, "invalid_grant", "The refresh token expired; sign in again.");
|
|
458
|
+
}
|
|
459
|
+
if (row.used_at !== null) {
|
|
460
|
+
const used = Date.parse(row.used_at);
|
|
461
|
+
forgetOld();
|
|
462
|
+
if (now() - used <= ROTATION_GRACE_MS) {
|
|
463
|
+
// A parallel refresh within the grace: the same successor (§18.5).
|
|
464
|
+
const kept = recent.get(hash);
|
|
465
|
+
if (kept) return answer(db, row.grant_id, kept.tokens);
|
|
466
|
+
return oauthError(
|
|
467
|
+
400,
|
|
468
|
+
"invalid_grant",
|
|
469
|
+
"This refresh token was just used; use its successor.",
|
|
470
|
+
);
|
|
471
|
+
}
|
|
472
|
+
// A refresh token used again after its grace: someone else holds it. The grant goes.
|
|
473
|
+
db.run('UPDATE "grant" SET revoked_at = ? WHERE id = ?', iso(now()), row.grant_id);
|
|
474
|
+
log.warn("auth.refresh_reused", { grant: row.grant_id });
|
|
475
|
+
return oauthError(
|
|
476
|
+
400,
|
|
477
|
+
"invalid_grant",
|
|
478
|
+
"The refresh token was used before; sign in again.",
|
|
479
|
+
);
|
|
480
|
+
}
|
|
481
|
+
const tokens = issue(db, row.grant_id);
|
|
482
|
+
db.run(
|
|
483
|
+
"UPDATE token SET used_at = ?, successor_hash = ? WHERE hash = ?",
|
|
484
|
+
iso(now()),
|
|
485
|
+
hashSecret(tokens.refresh),
|
|
486
|
+
hash,
|
|
487
|
+
);
|
|
488
|
+
forgetOld();
|
|
489
|
+
recent.set(hash, { tokens, at: now() });
|
|
490
|
+
return answer(db, row.grant_id, tokens);
|
|
491
|
+
});
|
|
492
|
+
}
|
|
493
|
+
return oauthError(400, "unsupported_grant_type", "Use the device grant or a refresh token.");
|
|
494
|
+
},
|
|
495
|
+
|
|
496
|
+
revoke(form) {
|
|
497
|
+
const presented = form.get("token") ?? "";
|
|
498
|
+
const hash = hashSecret(presented);
|
|
499
|
+
directory.write((db) => {
|
|
500
|
+
const row = db.get<{ grant_id: string | null }>(
|
|
501
|
+
"SELECT grant_id FROM token WHERE hash = ?",
|
|
502
|
+
hash,
|
|
503
|
+
);
|
|
504
|
+
if (row?.grant_id) {
|
|
505
|
+
db.run(
|
|
506
|
+
'UPDATE "grant" SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL',
|
|
507
|
+
iso(now()),
|
|
508
|
+
row.grant_id,
|
|
509
|
+
);
|
|
510
|
+
log.info("auth.revoked", { grant: row.grant_id });
|
|
511
|
+
}
|
|
512
|
+
});
|
|
513
|
+
},
|
|
514
|
+
|
|
515
|
+
authenticate(bearer) {
|
|
516
|
+
if (bearer.length < 20 || bearer.length > 200) return undefined;
|
|
517
|
+
const hash = hashSecret(bearer);
|
|
518
|
+
return directory.read((db) => {
|
|
519
|
+
const row = db.get<{
|
|
520
|
+
hash: string;
|
|
521
|
+
expires_at: string;
|
|
522
|
+
grant_id: string;
|
|
523
|
+
account_id: string;
|
|
524
|
+
link_id: string | null;
|
|
525
|
+
name: string | null;
|
|
526
|
+
}>(
|
|
527
|
+
`SELECT t.hash, t.expires_at, t.grant_id, g.account_id, g.link_id, a.name
|
|
528
|
+
FROM token t JOIN "grant" g ON g.id = t.grant_id JOIN account a ON a.id = g.account_id
|
|
529
|
+
WHERE t.hash = ? AND t.kind = 'access'`,
|
|
530
|
+
hash,
|
|
531
|
+
);
|
|
532
|
+
if (!row) return undefined;
|
|
533
|
+
// Constant-time on what was found, though the lookup was by hash already.
|
|
534
|
+
if (!timingSafeEqual(Buffer.from(row.hash), Buffer.from(hash))) return undefined;
|
|
535
|
+
const expiresAt = Date.parse(row.expires_at);
|
|
536
|
+
if (expiresAt <= now() || !grantLiveIn(db, row.grant_id)) return undefined;
|
|
537
|
+
const home = db.get<{ id: string }>(
|
|
538
|
+
"SELECT id FROM home WHERE owner_account_id = ?",
|
|
539
|
+
row.account_id,
|
|
540
|
+
);
|
|
541
|
+
if (!home) return undefined;
|
|
542
|
+
return {
|
|
543
|
+
accountId: row.account_id,
|
|
544
|
+
accountName: row.name ?? undefined,
|
|
545
|
+
grantId: row.grant_id,
|
|
546
|
+
homeId: home.id,
|
|
547
|
+
linkId: row.link_id ?? undefined,
|
|
548
|
+
expiresAt,
|
|
549
|
+
};
|
|
550
|
+
});
|
|
551
|
+
},
|
|
552
|
+
|
|
553
|
+
grantLive(grantId) {
|
|
554
|
+
return directory.read((db) => grantLiveIn(db, grantId));
|
|
555
|
+
},
|
|
556
|
+
|
|
557
|
+
pendingCode(code) {
|
|
558
|
+
const wanted = normalizeUserCode(code);
|
|
559
|
+
return directory.read((db) => {
|
|
560
|
+
const rows = db.all<{ data_json: string; expires_at: string }>(
|
|
561
|
+
"SELECT data_json, expires_at FROM token WHERE kind = 'device' AND expires_at > ?",
|
|
562
|
+
iso(now()),
|
|
563
|
+
);
|
|
564
|
+
const row = rows.find(
|
|
565
|
+
(candidate) => (JSON.parse(candidate.data_json) as DeviceState).userCode === wanted,
|
|
566
|
+
);
|
|
567
|
+
if (!row) return { ok: false as const, reason: "That code is unknown or has expired." };
|
|
568
|
+
const state = JSON.parse(row.data_json) as DeviceState;
|
|
569
|
+
return state.status === "pending"
|
|
570
|
+
? { ok: true as const }
|
|
571
|
+
: { ok: false as const, reason: "That code was already used." };
|
|
572
|
+
});
|
|
573
|
+
},
|
|
574
|
+
|
|
575
|
+
decide(input) {
|
|
576
|
+
const wanted = normalizeUserCode(input.code);
|
|
577
|
+
return directory.write((db) => {
|
|
578
|
+
const rows = db.all<{ hash: string; data_json: string }>(
|
|
579
|
+
"SELECT hash, data_json FROM token WHERE kind = 'device' AND expires_at > ?",
|
|
580
|
+
iso(now()),
|
|
581
|
+
);
|
|
582
|
+
const row = rows.find(
|
|
583
|
+
(candidate) => (JSON.parse(candidate.data_json) as DeviceState).userCode === wanted,
|
|
584
|
+
);
|
|
585
|
+
if (!row) return { ok: false as const, reason: "That code is unknown or has expired." };
|
|
586
|
+
const state = JSON.parse(row.data_json) as DeviceState;
|
|
587
|
+
if (state.status !== "pending")
|
|
588
|
+
return { ok: false as const, reason: "That code was already used." };
|
|
589
|
+
if (!input.approve) {
|
|
590
|
+
db.run(
|
|
591
|
+
"UPDATE token SET data_json = ? WHERE hash = ?",
|
|
592
|
+
JSON.stringify({ ...state, status: "denied" }),
|
|
593
|
+
row.hash,
|
|
594
|
+
);
|
|
595
|
+
return { ok: true as const };
|
|
596
|
+
}
|
|
597
|
+
const account = accountFor(db, input.identity);
|
|
598
|
+
db.run(
|
|
599
|
+
"INSERT INTO consent (account_id, client_id, granted_at) VALUES (?, ?, ?) ON CONFLICT (account_id, client_id) DO UPDATE SET revoked_at = NULL",
|
|
600
|
+
account,
|
|
601
|
+
CLI_CLIENT_ID,
|
|
602
|
+
iso(now()),
|
|
603
|
+
);
|
|
604
|
+
db.run(
|
|
605
|
+
"UPDATE token SET data_json = ? WHERE hash = ?",
|
|
606
|
+
JSON.stringify({ ...state, status: "approved", accountId: account }),
|
|
607
|
+
row.hash,
|
|
608
|
+
);
|
|
609
|
+
return { ok: true as const };
|
|
610
|
+
});
|
|
611
|
+
},
|
|
612
|
+
};
|
|
613
|
+
}
|