@dooc-dev/dooc 0.0.3 → 0.0.4

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.
@@ -56,6 +56,9 @@ export const createLocalPluginStorage = (userDir = process.env.DOOC_USER_DIR ??
56
56
  [...plugin.oauth.scopes].sort(),
57
57
  [...plugin.apiOrigins].sort(),
58
58
  plugin.oauth.authorizationParams ?? {},
59
+ ...(plugin.oauth.deviceAuthorizationUrl
60
+ ? [plugin.oauth.deviceAuthorizationUrl]
61
+ : []),
59
62
  ]))
60
63
  .digest("hex")}.json`;
61
64
  const credentials = {
@@ -10,5 +10,5 @@ export declare const httpsUrl: (source: string) => URL;
10
10
  /** Use after selecting a provider's user-token object in parseToken. */
11
11
  export declare const parseOAuthToken: (input: unknown) => OAuthToken;
12
12
  /** Bound both transfer time and decoded size; never include remote error bodies in errors. */
13
- export declare const fetchPluginJson: (url: string, init: RequestInit, tokenExchange?: boolean, transport?: typeof fetch) => Promise<unknown>;
13
+ export declare const fetchPluginJson: (url: string, init: RequestInit, tokenExchange?: boolean | "device", transport?: typeof fetch) => Promise<unknown>;
14
14
  export declare const validatePlugins: (input: unknown) => DataPlugin[];
@@ -59,7 +59,7 @@ export const fetchPluginJson = async (url, init, tokenExchange = false, transpor
59
59
  cache: "no-store",
60
60
  signal: AbortSignal.timeout(15_000),
61
61
  });
62
- if (!response.ok) {
62
+ if (!response.ok && !(tokenExchange === "device" && response.status === 400)) {
63
63
  await response.body?.cancel();
64
64
  throw new PluginError(response.status === 400 && tokenExchange
65
65
  ? 401
@@ -121,6 +121,8 @@ export const validatePlugins = (input) => {
121
121
  typeof oauth.clientId !== "string" ||
122
122
  !oauth.clientId.trim() ||
123
123
  (oauth.clientSecret !== undefined && typeof oauth.clientSecret !== "string") ||
124
+ (oauth.deviceAuthorizationUrl !== undefined &&
125
+ (typeof oauth.deviceAuthorizationUrl !== "string" || !!oauth.clientSecret)) ||
124
126
  !Array.isArray(oauth.scopes) ||
125
127
  oauth.scopes.some((s) => typeof s !== "string" || !s.trim()) ||
126
128
  typeof plugin.identifyUser !== "function" ||
@@ -133,7 +135,11 @@ export const validatePlugins = (input) => {
133
135
  !plugin.apiOrigins.length ||
134
136
  (oauth.parseToken !== undefined && typeof oauth.parseToken !== "function"))
135
137
  throw new Error(`Viewer plugins: invalid plugin ${plugin.id}`);
136
- for (const endpoint of [oauth.authorizationUrl, oauth.tokenUrl]) {
138
+ for (const endpoint of [
139
+ oauth.authorizationUrl,
140
+ oauth.tokenUrl,
141
+ ...(oauth.deviceAuthorizationUrl === undefined ? [] : [oauth.deviceAuthorizationUrl]),
142
+ ]) {
137
143
  if (typeof endpoint !== "string" || httpsUrl(endpoint).search)
138
144
  throw new Error("OAuth endpoints must not contain query parameters");
139
145
  }
@@ -8,6 +8,12 @@ export declare const createPluginRuntime: (definitions: readonly DataPlugin[], t
8
8
  createSession(): string;
9
9
  hasSession(id: string): boolean;
10
10
  connect(id: string, pluginId: string, redirectUri: string): string;
11
+ connectDevice(id: string, pluginId: string): Promise<string>;
12
+ pollDevice(id: string, pluginId: string, state: string): Promise<{
13
+ userCode: string;
14
+ verificationUri: string;
15
+ retryAfter: number;
16
+ } | undefined>;
11
17
  callback(id: string, pluginId: string, redirectUri: string, params: URLSearchParams): Promise<void>;
12
18
  disconnect(id: string, pluginId: string): void;
13
19
  status(id: string, pluginId: string): PluginUser | undefined;
@@ -23,16 +23,7 @@ export const createPluginRuntime = (definitions, transport, credentials) => {
23
23
  throw new PluginError(404, "Plugin is not configured");
24
24
  return plugin;
25
25
  };
26
- const exchange = async (plugin, fields) => {
27
- const { oauth } = plugin;
28
- const body = new URLSearchParams({ ...fields, client_id: oauth.clientId });
29
- if (oauth.clientSecret)
30
- body.set("client_secret", oauth.clientSecret);
31
- const result = await fetchPluginJson(oauth.tokenUrl, {
32
- method: "POST",
33
- body,
34
- headers: { accept: "application/json" },
35
- }, true, transport);
26
+ const tokenFrom = (plugin, result) => {
36
27
  if (!result ||
37
28
  typeof result !== "object" ||
38
29
  "error" in result ||
@@ -45,12 +36,24 @@ export const createPluginRuntime = (definitions, transport, credentials) => {
45
36
  throw new PluginError(502, "OAuth exchange failed");
46
37
  }
47
38
  try {
48
- return parseOAuthToken(oauth.parseToken ? oauth.parseToken(result) : result);
39
+ return parseOAuthToken(plugin.oauth.parseToken ? plugin.oauth.parseToken(result) : result);
49
40
  }
50
41
  catch {
51
42
  throw new PluginError(502, "Invalid OAuth token response");
52
43
  }
53
44
  };
45
+ const exchange = async (plugin, fields) => {
46
+ const { oauth } = plugin;
47
+ const body = new URLSearchParams({ ...fields, client_id: oauth.clientId });
48
+ if (oauth.clientSecret)
49
+ body.set("client_secret", oauth.clientSecret);
50
+ const result = await fetchPluginJson(oauth.tokenUrl, {
51
+ method: "POST",
52
+ body,
53
+ headers: { accept: "application/json" },
54
+ }, true, transport);
55
+ return tokenFrom(plugin, result);
56
+ };
54
57
  const context = (plugin, accessToken, write = false, check = () => { }) => ({
55
58
  request: async (source, init) => {
56
59
  check();
@@ -77,6 +80,34 @@ export const createPluginRuntime = (definitions, transport, credentials) => {
77
80
  if (sessionFor(id).connections.get(pluginId) !== connection)
78
81
  throw expired();
79
82
  };
83
+ const begin = (id, plugin, attempt) => {
84
+ const session = sessionFor(id);
85
+ session.connections.delete(plugin.id);
86
+ credentials?.set(plugin);
87
+ if (credentials)
88
+ for (const other of sessions.values())
89
+ other.connections.delete(plugin.id);
90
+ session.attempts.set(plugin.id, attempt);
91
+ };
92
+ const complete = async (id, plugin, attempt, token) => {
93
+ const expires = expiry(token);
94
+ const user = await plugin.identifyUser(context(plugin, token.access_token));
95
+ if (!user ||
96
+ typeof user.id !== "string" ||
97
+ !user.id ||
98
+ typeof user.name !== "string" ||
99
+ !user.name ||
100
+ user.id.length > 512 ||
101
+ user.name.length > 512)
102
+ throw new PluginError(502, "Plugin could not identify the authorized user");
103
+ const session = sessionFor(id);
104
+ if (session.attempts.get(plugin.id) !== attempt || attempt.expires <= Date.now())
105
+ throw expired();
106
+ session.attempts.delete(plugin.id);
107
+ const connection = { token, expires, user: { id: user.id, name: user.name } };
108
+ credentials?.set(plugin, connection);
109
+ session.connections.set(plugin.id, connection);
110
+ };
80
111
  const unregister = (pluginId) => {
81
112
  plugins.delete(pluginId);
82
113
  for (const session of sessions.values()) {
@@ -217,8 +248,9 @@ export const createPluginRuntime = (definitions, transport, credentials) => {
217
248
  }
218
249
  },
219
250
  connect(id, pluginId, redirectUri) {
220
- const session = sessionFor(id);
221
251
  const plugin = pluginFor(pluginId);
252
+ if (plugin.oauth.deviceAuthorizationUrl)
253
+ throw new PluginError(400, "Use device authorization for this plugin");
222
254
  const redirect = new URL(redirectUri);
223
255
  if (redirect.protocol !== "http:" ||
224
256
  !["localhost", "127.0.0.1", "[::1]"].includes(redirect.hostname) ||
@@ -234,12 +266,7 @@ export const createPluginRuntime = (definitions, transport, credentials) => {
234
266
  redirectUri,
235
267
  expires: Date.now() + 10 * 60 * 1000,
236
268
  };
237
- session.connections.delete(pluginId);
238
- credentials?.set(plugin);
239
- if (credentials)
240
- for (const other of sessions.values())
241
- other.connections.delete(pluginId);
242
- session.attempts.set(pluginId, attempt);
269
+ begin(id, plugin, attempt);
243
270
  const url = new URL(plugin.oauth.authorizationUrl);
244
271
  for (const [key, value] of Object.entries(plugin.oauth.authorizationParams ?? {}))
245
272
  url.searchParams.set(key, value);
@@ -255,11 +282,131 @@ export const createPluginRuntime = (definitions, transport, credentials) => {
255
282
  url.searchParams.set(key, value);
256
283
  return url.href;
257
284
  },
285
+ async connectDevice(id, pluginId) {
286
+ const plugin = pluginFor(pluginId);
287
+ if (!plugin.oauth.deviceAuthorizationUrl)
288
+ throw new PluginError(400, "Device authorization is not configured");
289
+ const attempt = {
290
+ state: nonce(),
291
+ expires: Date.now() + 15 * 60_000,
292
+ deviceCode: "",
293
+ userCode: "",
294
+ verificationUri: "",
295
+ interval: 5,
296
+ nextPoll: Infinity,
297
+ polling: false,
298
+ };
299
+ begin(id, plugin, attempt);
300
+ try {
301
+ const result = (await fetchPluginJson(plugin.oauth.deviceAuthorizationUrl, {
302
+ method: "POST",
303
+ headers: { accept: "application/json" },
304
+ body: new URLSearchParams({
305
+ client_id: plugin.oauth.clientId,
306
+ [plugin.oauth.scopeParameter ?? "scope"]: plugin.oauth.scopes.join(plugin.oauth.scopeSeparator ?? " "),
307
+ }),
308
+ }, true, transport));
309
+ if (!result ||
310
+ typeof result.device_code !== "string" ||
311
+ !result.device_code ||
312
+ result.device_code.length > 4096 ||
313
+ typeof result.user_code !== "string" ||
314
+ !result.user_code ||
315
+ result.user_code.length > 128 ||
316
+ typeof result.verification_uri !== "string" ||
317
+ result.verification_uri.length > 2048 ||
318
+ typeof result.expires_in !== "number" ||
319
+ !Number.isFinite(result.expires_in) ||
320
+ result.expires_in <= 0 ||
321
+ result.expires_in > 3600 ||
322
+ (result.interval !== undefined &&
323
+ (typeof result.interval !== "number" ||
324
+ !Number.isFinite(result.interval) ||
325
+ result.interval <= 0 ||
326
+ result.interval > 60)))
327
+ throw new PluginError(502, "Invalid device authorization response");
328
+ const verificationUri = httpsUrl(result.verification_uri).href;
329
+ if (sessionFor(id).attempts.get(pluginId) !== attempt)
330
+ throw expired();
331
+ Object.assign(attempt, {
332
+ deviceCode: result.device_code,
333
+ userCode: result.user_code,
334
+ verificationUri,
335
+ expires: Date.now() + result.expires_in * 1000,
336
+ interval: result.interval ?? 5,
337
+ nextPoll: Date.now() + Number(result.interval ?? 5) * 1000,
338
+ });
339
+ return attempt.state;
340
+ }
341
+ catch (error) {
342
+ if (sessionFor(id).attempts.get(pluginId) === attempt)
343
+ sessionFor(id).attempts.delete(pluginId);
344
+ throw error;
345
+ }
346
+ },
347
+ async pollDevice(id, pluginId, state) {
348
+ const session = sessionFor(id);
349
+ const plugin = pluginFor(pluginId);
350
+ const attempt = session.attempts.get(pluginId);
351
+ if (!state ||
352
+ !attempt ||
353
+ !("deviceCode" in attempt) ||
354
+ !attempt.deviceCode ||
355
+ attempt.state !== state ||
356
+ attempt.expires <= Date.now())
357
+ throw new PluginError(400, "Invalid or expired device authorization");
358
+ if (!attempt.polling && Date.now() >= attempt.nextPoll) {
359
+ attempt.polling = true;
360
+ attempt.nextPoll = Date.now() + attempt.interval * 1000;
361
+ try {
362
+ const result = await fetchPluginJson(plugin.oauth.tokenUrl, {
363
+ method: "POST",
364
+ headers: { accept: "application/json" },
365
+ body: new URLSearchParams({
366
+ client_id: plugin.oauth.clientId,
367
+ device_code: attempt.deviceCode,
368
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
369
+ }),
370
+ }, "device", transport);
371
+ if (sessionFor(id).attempts.get(pluginId) !== attempt ||
372
+ attempt.expires <= Date.now())
373
+ throw expired();
374
+ if (result && typeof result === "object" && "error" in result) {
375
+ if (result.error === "slow_down") {
376
+ attempt.interval += 5;
377
+ if ("interval" in result &&
378
+ typeof result.interval === "number" &&
379
+ Number.isFinite(result.interval) &&
380
+ result.interval > attempt.interval)
381
+ attempt.interval = result.interval;
382
+ }
383
+ else if (result.error !== "authorization_pending") {
384
+ session.attempts.delete(pluginId);
385
+ throw new PluginError(400, "Device sign-in was not completed. Connect this plugin again.");
386
+ }
387
+ }
388
+ else {
389
+ await complete(id, plugin, attempt, tokenFrom(plugin, result));
390
+ return;
391
+ }
392
+ }
393
+ finally {
394
+ attempt.polling = false;
395
+ attempt.nextPoll = Date.now() + attempt.interval * 1000;
396
+ }
397
+ }
398
+ return {
399
+ userCode: attempt.userCode,
400
+ verificationUri: attempt.verificationUri,
401
+ retryAfter: Math.max(1, Math.ceil((Math.min(attempt.nextPoll, attempt.expires) - Date.now()) / 1000)),
402
+ };
403
+ },
258
404
  async callback(id, pluginId, redirectUri, params) {
259
405
  const session = sessionFor(id);
260
406
  const plugin = pluginFor(pluginId);
261
407
  const attempt = session.attempts.get(pluginId);
262
408
  if (!attempt?.state ||
409
+ !("verifier" in attempt) ||
263
410
  attempt.expires <= Date.now() ||
264
411
  attempt.redirectUri !== redirectUri ||
265
412
  params.getAll("state").length !== 1 ||
@@ -276,22 +423,7 @@ export const createPluginRuntime = (definitions, transport, credentials) => {
276
423
  redirect_uri: redirectUri,
277
424
  code_verifier: attempt.verifier,
278
425
  });
279
- const expires = expiry(token);
280
- const user = await plugin.identifyUser(context(plugin, token.access_token));
281
- if (!user ||
282
- typeof user.id !== "string" ||
283
- !user.id ||
284
- typeof user.name !== "string" ||
285
- !user.name ||
286
- user.id.length > 512 ||
287
- user.name.length > 512)
288
- throw new PluginError(502, "Plugin could not identify the authorized user");
289
- if (sessionFor(id).attempts.get(pluginId) !== attempt)
290
- throw expired();
291
- session.attempts.delete(pluginId);
292
- const connection = { token, expires, user: { id: user.id, name: user.name } };
293
- credentials?.set(plugin, connection);
294
- session.connections.set(pluginId, connection);
426
+ await complete(id, plugin, attempt, token);
295
427
  },
296
428
  disconnect(id, pluginId) {
297
429
  const session = sessionFor(id);
@@ -1,9 +1,11 @@
1
- /** OAuth credentials belong in environment variables, never in document source. */
1
+ /** Distributors bundle public client IDs; secrets stay on trusted servers, never in plugin ZIPs. */
2
2
  export interface PluginOAuth {
3
3
  authorizationUrl: string;
4
4
  tokenUrl: string;
5
5
  clientId: string;
6
6
  clientSecret?: string;
7
+ /** Public clients may use the device grant instead of a browser callback. */
8
+ deviceAuthorizationUrl?: string;
7
9
  scopes: readonly string[];
8
10
  /** Provider-specific user authorization parameters, such as actor=user. */
9
11
  authorizationParams?: Readonly<Record<string, string>>;