pico-engine 1.4.0 → 1.5.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/src/server.ts CHANGED
@@ -1,27 +1,89 @@
1
1
  import * as bodyParser from "body-parser";
2
2
  import * as express from "express";
3
- import { Express, Request } from "express";
3
+ import { Express, Request, Response } from "express";
4
4
  import helmet from "helmet";
5
5
  import * as _ from "lodash";
6
6
  import * as path from "path";
7
7
  import { PicoEngineCore } from "pico-engine-core";
8
+ import { PicoFramework } from "pico-framework";
9
+ import { AuthError, AuthService } from "./auth";
10
+ import { OAuthError, OAuthService, parseApproveBody, parseAuthorizeQuery, renderConsentHtml } from "./oauth";
8
11
 
9
12
  const engineVersion = require("../package.json").version;
10
13
 
14
+ const SESSION_COOKIE = "pico-session";
15
+ const CEREMONY_COOKIE = "pico-ceremony";
16
+
17
+ function localhostChannelBypassEnabled(): boolean {
18
+ return process.env.PICO_ENGINE_ALLOW_LOCALHOST_C !== "0";
19
+ }
20
+
11
21
  function mergeGetPost(req: Request) {
12
22
  // give preference to post body params
13
23
  return _.assign({}, req.query, req.body, { _headers: req.headers });
14
24
  }
15
25
 
16
- export function server(core: PicoEngineCore, uiECI: string): Express {
26
+ function parseCookies(req: Request): { [name: string]: string } {
27
+ const header = req.headers.cookie;
28
+ const out: { [name: string]: string } = {};
29
+ if (typeof header !== "string") {
30
+ return out;
31
+ }
32
+ for (const part of header.split(";")) {
33
+ const idx = part.indexOf("=");
34
+ if (idx < 0) {
35
+ continue;
36
+ }
37
+ const name = part.slice(0, idx).trim();
38
+ const value = part.slice(idx + 1).trim();
39
+ if (name) {
40
+ out[name] = decodeURIComponent(value);
41
+ }
42
+ }
43
+ return out;
44
+ }
45
+
46
+ function isLocalhostAddress(addr: string | undefined): boolean {
47
+ if (!addr) {
48
+ return false;
49
+ }
50
+ const normalized = addr.replace(/^::ffff:/, "");
51
+ return normalized === "127.0.0.1" || normalized === "::1";
52
+ }
53
+
54
+ function isLocalhostRequest(req: Request): boolean {
55
+ if (isLocalhostAddress(req.ip)) {
56
+ return true;
57
+ }
58
+ if (isLocalhostAddress(req.socket?.remoteAddress)) {
59
+ return true;
60
+ }
61
+ const host = req.headers.host || "";
62
+ return host.startsWith("localhost:") || host.startsWith("127.0.0.1:");
63
+ }
64
+
65
+ export function server(
66
+ core: PicoEngineCore,
67
+ uiECI: string | null,
68
+ auth?: AuthService,
69
+ oauth?: OAuthService
70
+ ): Express {
71
+ const pf = core.picoFramework;
17
72
  const app = express();
18
73
 
19
74
  app.use(function(req, res, next) {
75
+ // /auth routes need a specific credentialed CORS origin (below), not "*".
76
+ if (req.path.indexOf("/auth") === 0) {
77
+ return next();
78
+ }
20
79
  res.header("Access-Control-Allow-Origin", "*");
21
- res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
80
+ res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
22
81
  next();
23
82
  });
24
83
  app.use('*',(req,res,next) =>{
84
+ if (req.path.indexOf("/auth") === 0) {
85
+ return next();
86
+ }
25
87
  if (req.method == "OPTIONS") {
26
88
  res.header("Allow", "POST, GET, OPTIONS");
27
89
  res.header("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
@@ -33,16 +95,22 @@ export function server(core: PicoEngineCore, uiECI: string): Express {
33
95
  });
34
96
  // Helmet 7+ CSP defaults include upgrade-insecure-requests, which breaks the
35
97
  // UI on plain HTTP (browser upgrades /api/* to https and TLS fails).
36
- app.use(
37
- helmet({
38
- contentSecurityPolicy: {
39
- directives: {
40
- ...helmet.contentSecurityPolicy.getDefaultDirectives(),
41
- "upgrade-insecure-requests": null,
42
- },
98
+ // OAuth consent pages must not use form-action 'self' — after Allow, the
99
+ // browser follows a redirect to the app's redirect_uri (external origin).
100
+ const defaultHelmet = helmet({
101
+ contentSecurityPolicy: {
102
+ directives: {
103
+ ...helmet.contentSecurityPolicy.getDefaultDirectives(),
104
+ "upgrade-insecure-requests": null,
43
105
  },
44
- })
45
- );
106
+ },
107
+ });
108
+ app.use(function (req, res, next) {
109
+ if (req.path === "/oauth/authorize" || req.path === "/oauth/approve") {
110
+ return helmet({ contentSecurityPolicy: false })(req, res, next);
111
+ }
112
+ return defaultHelmet(req, res, next);
113
+ });
46
114
  app.use(express.static(path.resolve(__dirname, "..", "public")));
47
115
  app.use(
48
116
  bodyParser.json({
@@ -61,11 +129,146 @@ export function server(core: PicoEngineCore, uiECI: string): Express {
61
129
  })
62
130
  );
63
131
 
132
+ if (auth) {
133
+ registerAuthRoutes(app, auth);
134
+ }
135
+
136
+ function isEciInRootTree(rootPicoId: string, eci: string): boolean {
137
+ try {
138
+ let pico = pf.getPico(eci);
139
+ while (pico) {
140
+ if (pico.id === rootPicoId) {
141
+ return true;
142
+ }
143
+ if (!pico.parent) {
144
+ return false;
145
+ }
146
+ pico = pf.getPico(pico.parent);
147
+ }
148
+ } catch (_e) {
149
+ return false;
150
+ }
151
+ return false;
152
+ }
153
+
154
+ function requireAuthSession(
155
+ req: Request,
156
+ res: Response,
157
+ next: express.NextFunction
158
+ ) {
159
+ if (!auth) {
160
+ next();
161
+ return;
162
+ }
163
+ const token = parseCookies(req)[SESSION_COOKIE] || "";
164
+ auth
165
+ .getSession(token)
166
+ .then((session) => {
167
+ if (!session) {
168
+ res.status(401).json({ error: "Not authenticated" });
169
+ return;
170
+ }
171
+ const eci = req.params.eci;
172
+ if (eci && !isEciInRootTree(session.rootPicoId, eci)) {
173
+ res.status(403).json({ error: "Not authorized for this pico" });
174
+ return;
175
+ }
176
+ (req as any).picoSession = session;
177
+ next();
178
+ })
179
+ .catch(next);
180
+ }
181
+
182
+ /** `/c/*` is internal: passkey session, or localhost for in-engine HTTP loops. */
183
+ function requireChannelSession(
184
+ req: Request,
185
+ res: Response,
186
+ next: express.NextFunction
187
+ ) {
188
+ if (!auth) {
189
+ next();
190
+ return;
191
+ }
192
+ if (localhostChannelBypassEnabled() && isLocalhostRequest(req)) {
193
+ next();
194
+ return;
195
+ }
196
+ requireAuthSession(req, res, next);
197
+ }
198
+
199
+ /** External Sky API: Bearer when channel is oauth-webhook or mesh has OAuth ruleset. */
200
+ function requireSkyBearerIfOAuth(
201
+ req: Request,
202
+ res: Response,
203
+ next: express.NextFunction
204
+ ) {
205
+ if (!oauth) {
206
+ next();
207
+ return;
208
+ }
209
+ const eci = req.params.eci;
210
+ if (!eci) {
211
+ next();
212
+ return;
213
+ }
214
+ oauth
215
+ .skyRequiresBearer(eci)
216
+ .then((required) => {
217
+ if (!required) {
218
+ next();
219
+ return;
220
+ }
221
+ const header = req.headers.authorization;
222
+ if (typeof header !== "string" || !header.startsWith("Bearer ")) {
223
+ res.status(401).json({ error: "Bearer token required" });
224
+ return;
225
+ }
226
+ const token = header.slice("Bearer ".length).trim();
227
+ return oauth.validateSkyBearerToken(token, eci).then((valid) => {
228
+ if (!valid) {
229
+ res.status(401).json({ error: "Invalid or expired token" });
230
+ return;
231
+ }
232
+ next();
233
+ });
234
+ })
235
+ .catch(next);
236
+ }
237
+
238
+ if (oauth) {
239
+ registerOAuthRoutes(app, oauth, auth, requireAuthSession, parseCookies);
240
+ }
241
+
64
242
  app.get("/api/ui-context", function (req, res, next) {
65
- res.json({ version: engineVersion, eci: uiECI });
243
+ const hasRoots = pf.rootPicos().length > 0;
244
+ const base: any = {
245
+ version: engineVersion,
246
+ hasRoots,
247
+ allowSelfSignup: auth ? auth.allowSelfSignup() : false,
248
+ };
249
+ if (!auth) {
250
+ base.eci = uiECI;
251
+ res.json(base);
252
+ return;
253
+ }
254
+ const token = parseCookies(req)[SESSION_COOKIE] || "";
255
+ auth
256
+ .needsAuthMigration()
257
+ .then((needsAuthMigration) => {
258
+ base.needsAuthMigration = needsAuthMigration;
259
+ return auth.whoami(token);
260
+ })
261
+ .then((who) => {
262
+ base.session = who;
263
+ if (who.authenticated && who.uiECI) {
264
+ base.eci = who.uiECI;
265
+ }
266
+ res.json(base);
267
+ })
268
+ .catch(next);
66
269
  });
67
270
 
68
- app.all("/api/flush", function (req, res, next) {
271
+ app.all("/api/flush", requireAuthSession, function (req, res, next) {
69
272
  const attrs = mergeGetPost(req);
70
273
  const url = attrs["url"];
71
274
  if (typeof url !== "string") {
@@ -86,7 +289,7 @@ export function server(core: PicoEngineCore, uiECI: string): Express {
86
289
  }
87
290
  });
88
291
 
89
- app.all("/c/:eci/event/:domain/:name", function (req, res, next) {
292
+ app.all("/c/:eci/event/:domain/:name", requireChannelSession, function (req, res, next) {
90
293
  core
91
294
  .event({
92
295
  eci: req.params.eci,
@@ -101,7 +304,7 @@ export function server(core: PicoEngineCore, uiECI: string): Express {
101
304
  .catch(next);
102
305
  });
103
306
 
104
- app.all("/c/:eci/event-wait/:domain/:name", function (req, res, next) {
307
+ app.all("/c/:eci/event-wait/:domain/:name", requireChannelSession, function (req, res, next) {
105
308
  core
106
309
  .eventWait({
107
310
  eci: req.params.eci,
@@ -116,7 +319,7 @@ export function server(core: PicoEngineCore, uiECI: string): Express {
116
319
  .catch(next);
117
320
  });
118
321
 
119
- app.all("/sky/event/:eci/:eid/:domain/:type", function (req, res, next) {
322
+ app.all("/sky/event/:eci/:eid/:domain/:type", requireSkyBearerIfOAuth, function (req, res, next) {
120
323
  const attrs = mergeGetPost(req);
121
324
  if (req.params.eid !== "none" && !attrs.hasOwnProperty("__eid")) {
122
325
  attrs.__eid = req.params.eid;
@@ -155,6 +358,7 @@ export function server(core: PicoEngineCore, uiECI: string): Express {
155
358
 
156
359
  app.all(
157
360
  "/c/:eci/event/:domain/:name/query/:rid/:qname",
361
+ requireChannelSession,
158
362
  function (req, res, next) {
159
363
  const attrs = mergeGetPost(req);
160
364
  core
@@ -180,8 +384,8 @@ export function server(core: PicoEngineCore, uiECI: string): Express {
180
384
  }
181
385
  );
182
386
 
183
- app.all("/c/:eci/query/:rid/:name", function (req, res, next) {
184
- const funcPart = req.params.name.split(".");
387
+ function handleSkyQuery(req: Request, res: Response, next: express.NextFunction) {
388
+ const funcPart = req.params["function"].split(".");
185
389
  core
186
390
  .query({
187
391
  eci: req.params.eci,
@@ -189,7 +393,7 @@ export function server(core: PicoEngineCore, uiECI: string): Express {
189
393
  name: funcPart[0],
190
394
  args: mergeGetPost(req),
191
395
  })
192
- .then((data) => {
396
+ .then((data: any) => {
193
397
  if (funcPart[1] === "html") {
194
398
  res.header("Content-Type", "text/html");
195
399
  res.end(data);
@@ -201,10 +405,10 @@ export function server(core: PicoEngineCore, uiECI: string): Express {
201
405
  }
202
406
  })
203
407
  .catch(next);
204
- });
408
+ }
205
409
 
206
- app.all("/sky/cloud/:eci/:rid/:function", function (req, res, next) {
207
- const funcPart = req.params["function"].split(".");
410
+ app.all("/c/:eci/query/:rid/:name", requireChannelSession, function (req, res, next) {
411
+ const funcPart = req.params.name.split(".");
208
412
  core
209
413
  .query({
210
414
  eci: req.params.eci,
@@ -212,7 +416,7 @@ export function server(core: PicoEngineCore, uiECI: string): Express {
212
416
  name: funcPart[0],
213
417
  args: mergeGetPost(req),
214
418
  })
215
- .then((data) => {
419
+ .then((data: any) => {
216
420
  if (funcPart[1] === "html") {
217
421
  res.header("Content-Type", "text/html");
218
422
  res.end(data);
@@ -226,12 +430,24 @@ export function server(core: PicoEngineCore, uiECI: string): Express {
226
430
  .catch(next);
227
431
  });
228
432
 
433
+ app.all("/sky/query/:eci/:rid/:function", requireSkyBearerIfOAuth, handleSkyQuery);
434
+ // Legacy alias; prefer /sky/query/ per Sky Query API docs.
435
+ app.all("/sky/cloud/:eci/:rid/:function", requireSkyBearerIfOAuth, handleSkyQuery);
436
+
229
437
  app.use(function (
230
438
  err: any,
231
439
  req: express.Request,
232
440
  res: express.Response,
233
441
  next: express.NextFunction
234
442
  ) {
443
+ if (err instanceof AuthError) {
444
+ res.status(err.statusCode).json({ error: err.message });
445
+ return;
446
+ }
447
+ if (err instanceof OAuthError) {
448
+ res.status(err.statusCode).json({ error: err.oauthError, error_description: err.message });
449
+ return;
450
+ }
235
451
  let message = err + "";
236
452
  console.error(err);
237
453
  if (err?.krl_compiler?.loc?.start) {
@@ -259,3 +475,406 @@ export function server(core: PicoEngineCore, uiECI: string): Express {
259
475
 
260
476
  return app;
261
477
  }
478
+
479
+ function registerAuthRoutes(app: Express, auth: AuthService) {
480
+ function setSessionCookie(res: Response, token: string, expiry: number) {
481
+ res.cookie(SESSION_COOKIE, token, {
482
+ httpOnly: true,
483
+ sameSite: "lax",
484
+ secure: auth.isSecure(),
485
+ path: "/",
486
+ expires: new Date(expiry),
487
+ });
488
+ }
489
+
490
+ function setCeremonyCookie(res: Response, ceremonyId: string) {
491
+ res.cookie(CEREMONY_COOKIE, ceremonyId, {
492
+ httpOnly: true,
493
+ sameSite: "lax",
494
+ secure: auth.isSecure(),
495
+ path: "/",
496
+ maxAge: 5 * 60 * 1000,
497
+ });
498
+ }
499
+
500
+ function clearCeremonyCookie(res: Response) {
501
+ res.clearCookie(CEREMONY_COOKIE, { path: "/" });
502
+ }
503
+
504
+ // WebAuthn requires a specific, credentialed origin — never "*".
505
+ app.use("/auth", function (req, res, next) {
506
+ res.header("Access-Control-Allow-Origin", auth.rp().origin);
507
+ res.header("Access-Control-Allow-Credentials", "true");
508
+ res.header(
509
+ "Access-Control-Allow-Headers",
510
+ "Origin, X-Requested-With, Content-Type, Accept"
511
+ );
512
+ res.header(
513
+ "Access-Control-Allow-Methods",
514
+ "POST, GET, DELETE, OPTIONS"
515
+ );
516
+ res.header("Vary", "Origin");
517
+ if (req.method === "OPTIONS") {
518
+ res.status(204).end();
519
+ return;
520
+ }
521
+ next();
522
+ });
523
+
524
+ function requireSession(req: Request, res: Response, next: express.NextFunction) {
525
+ const token = parseCookies(req)[SESSION_COOKIE] || "";
526
+ auth
527
+ .getSession(token)
528
+ .then((session) => {
529
+ if (!session) {
530
+ res.status(401).json({ error: "Not authenticated" });
531
+ return;
532
+ }
533
+ (req as any).picoSession = session;
534
+ next();
535
+ })
536
+ .catch(next);
537
+ }
538
+
539
+ app.post("/auth/register/options", function (req, res, next) {
540
+ auth
541
+ .registerNewAccountOptions({
542
+ displayName: req.body && req.body.displayName,
543
+ invite: req.body && req.body.invite,
544
+ })
545
+ .then(({ options, ceremonyId }) => {
546
+ setCeremonyCookie(res, ceremonyId);
547
+ res.json(options);
548
+ })
549
+ .catch(next);
550
+ });
551
+
552
+ app.post("/auth/register/verify", function (req, res, next) {
553
+ const ceremonyId = parseCookies(req)[CEREMONY_COOKIE] || "";
554
+ auth
555
+ .registerNewAccountVerify({ ceremonyId, response: req.body })
556
+ .then(({ account, session, uiECI }) => {
557
+ clearCeremonyCookie(res);
558
+ setSessionCookie(res, session.token, session.expiry);
559
+ res.json({
560
+ verified: true,
561
+ accountId: account.accountId,
562
+ rootPicoId: account.rootPicoId,
563
+ uiECI,
564
+ });
565
+ })
566
+ .catch(next);
567
+ });
568
+
569
+ app.post("/auth/claim/options", function (req, res, next) {
570
+ auth
571
+ .claimPrimaryRootOptions({ displayName: req.body && req.body.displayName })
572
+ .then(({ options, ceremonyId }) => {
573
+ setCeremonyCookie(res, ceremonyId);
574
+ res.json(options);
575
+ })
576
+ .catch(next);
577
+ });
578
+
579
+ app.post("/auth/claim/verify", function (req, res, next) {
580
+ const ceremonyId = parseCookies(req)[CEREMONY_COOKIE] || "";
581
+ auth
582
+ .claimPrimaryRootVerify({ ceremonyId, response: req.body })
583
+ .then(({ account, session, uiECI }) => {
584
+ clearCeremonyCookie(res);
585
+ setSessionCookie(res, session.token, session.expiry);
586
+ res.json({
587
+ verified: true,
588
+ accountId: account.accountId,
589
+ rootPicoId: account.rootPicoId,
590
+ uiECI,
591
+ });
592
+ })
593
+ .catch(next);
594
+ });
595
+
596
+ app.post("/auth/login/options", function (req, res, next) {
597
+ auth
598
+ .loginOptions()
599
+ .then(({ options, ceremonyId }) => {
600
+ setCeremonyCookie(res, ceremonyId);
601
+ res.json(options);
602
+ })
603
+ .catch(next);
604
+ });
605
+
606
+ app.post("/auth/login/verify", function (req, res, next) {
607
+ const ceremonyId = parseCookies(req)[CEREMONY_COOKIE] || "";
608
+ auth
609
+ .loginVerify({ ceremonyId, response: req.body })
610
+ .then(({ account, session }) => {
611
+ clearCeremonyCookie(res);
612
+ setSessionCookie(res, session.token, session.expiry);
613
+ res.json({
614
+ verified: true,
615
+ accountId: account.accountId,
616
+ rootPicoId: account.rootPicoId,
617
+ });
618
+ })
619
+ .catch(next);
620
+ });
621
+
622
+ app.post("/auth/logout", function (req, res, next) {
623
+ const token = parseCookies(req)[SESSION_COOKIE] || "";
624
+ auth
625
+ .deleteSession(token)
626
+ .then(() => {
627
+ res.clearCookie(SESSION_COOKIE, { path: "/" });
628
+ res.json({ ok: true });
629
+ })
630
+ .catch(next);
631
+ });
632
+
633
+ app.get("/auth/session", function (req, res, next) {
634
+ const token = parseCookies(req)[SESSION_COOKIE] || "";
635
+ auth
636
+ .whoami(token)
637
+ .then((who) => res.json(who))
638
+ .catch(next);
639
+ });
640
+
641
+ app.post("/auth/credentials/options", requireSession, function (req, res, next) {
642
+ const session = (req as any).picoSession;
643
+ auth
644
+ .addCredentialOptions({ accountId: session.accountId })
645
+ .then(({ options, ceremonyId }) => {
646
+ setCeremonyCookie(res, ceremonyId);
647
+ res.json(options);
648
+ })
649
+ .catch(next);
650
+ });
651
+
652
+ app.post("/auth/credentials/verify", requireSession, function (req, res, next) {
653
+ const session = (req as any).picoSession;
654
+ const ceremonyId = parseCookies(req)[CEREMONY_COOKIE] || "";
655
+ auth
656
+ .addCredentialVerify({
657
+ ceremonyId,
658
+ accountId: session.accountId,
659
+ response: req.body,
660
+ label: req.body && req.body.label,
661
+ })
662
+ .then(({ credential }) => {
663
+ clearCeremonyCookie(res);
664
+ res.json({ verified: true, credential });
665
+ })
666
+ .catch(next);
667
+ });
668
+
669
+ app.delete("/auth/credentials/:id", requireSession, function (req, res, next) {
670
+ const session = (req as any).picoSession;
671
+ auth
672
+ .deleteCredential(session.accountId, req.params.id)
673
+ .then(() => res.json({ ok: true }))
674
+ .catch(next);
675
+ });
676
+
677
+ app.get("/auth/invites/:token", function (req, res, next) {
678
+ auth
679
+ .peekInvite(req.params.token)
680
+ .then((peek) => res.json(peek))
681
+ .catch(next);
682
+ });
683
+
684
+ app.post("/auth/invites", requireSession, function (req, res, next) {
685
+ const session = (req as any).picoSession;
686
+ auth
687
+ .createInvite({
688
+ createdByAccountId: session.accountId,
689
+ label: req.body && req.body.label,
690
+ })
691
+ .then((invite) => res.json(invite))
692
+ .catch(next);
693
+ });
694
+ }
695
+
696
+ function registerOAuthRoutes(
697
+ app: Express,
698
+ oauth: OAuthService,
699
+ auth: AuthService | undefined,
700
+ requireAuthSession: (
701
+ req: Request,
702
+ res: Response,
703
+ next: express.NextFunction
704
+ ) => void,
705
+ parseCookiesFn: (req: Request) => { [name: string]: string }
706
+ ) {
707
+ function requireOAuthSession(
708
+ req: Request,
709
+ res: Response,
710
+ next: express.NextFunction
711
+ ) {
712
+ if (!auth) {
713
+ res.status(503).json({ error: "Authentication is not configured" });
714
+ return;
715
+ }
716
+ const token = parseCookiesFn(req)[SESSION_COOKIE] || "";
717
+ auth
718
+ .getSession(token)
719
+ .then((session) => {
720
+ if (!session) {
721
+ res.status(401).json({ error: "Not authenticated" });
722
+ return;
723
+ }
724
+ (req as any).picoSession = session;
725
+ next();
726
+ })
727
+ .catch(next);
728
+ }
729
+
730
+ app.post("/oauth/token", function (req, res, next) {
731
+ // Prefer body, but accept query params too (manual/browser testing).
732
+ const body = _.assign({}, req.query, req.body);
733
+ oauth
734
+ .tokenGrant(body)
735
+ .then((token) => res.json(token))
736
+ .catch(next);
737
+ });
738
+
739
+ // Browser-friendly alias for manual token exchange during development.
740
+ app.get("/oauth/token", function (req, res, next) {
741
+ oauth
742
+ .tokenGrant(req.query as Record<string, unknown>)
743
+ .then((token) => res.json(token))
744
+ .catch(next);
745
+ });
746
+
747
+ app.get("/oauth/authorize", function (req, res, next) {
748
+ let params;
749
+ try {
750
+ params = parseAuthorizeQuery(req.query as Record<string, unknown>);
751
+ } catch (err) {
752
+ next(err);
753
+ return;
754
+ }
755
+ oauth
756
+ .getAppForAuthorize(params)
757
+ .then(async (appRecord) => {
758
+ if (!auth) {
759
+ res.status(503).send("Authentication is not configured");
760
+ return;
761
+ }
762
+ const token = parseCookiesFn(req)[SESSION_COOKIE] || "";
763
+ const session = await auth.getSession(token);
764
+ if (!session) {
765
+ const returnPath = req.originalUrl || "/oauth/authorize";
766
+ res.redirect(
767
+ "/?oauth_return=" + encodeURIComponent(returnPath)
768
+ );
769
+ return;
770
+ }
771
+ if (session.rootPicoId !== appRecord.rootPicoId) {
772
+ res.status(403).send("Signed in to a different mesh");
773
+ return;
774
+ }
775
+ res.type("html").send(renderConsentHtml(appRecord, params));
776
+ })
777
+ .catch(next);
778
+ });
779
+
780
+ app.post("/oauth/approve", function (req, res, next) {
781
+ if (!auth) {
782
+ res.status(503).send("Authentication is not configured");
783
+ return;
784
+ }
785
+ const token = parseCookiesFn(req)[SESSION_COOKIE] || "";
786
+ auth
787
+ .getSession(token)
788
+ .then((session) => {
789
+ if (!session) {
790
+ res.status(401).send("Not authenticated");
791
+ return;
792
+ }
793
+ const params = parseApproveBody(req.body || {});
794
+ return oauth
795
+ .approveAuthorization(session, params)
796
+ .then((redirectUrl) => {
797
+ // 303 See Other: browser must follow with GET (OAuth code in query string).
798
+ res.redirect(303, redirectUrl);
799
+ });
800
+ })
801
+ .catch((err) => {
802
+ if (err instanceof OAuthError) {
803
+ const redirect_uri = String(req.body?.redirect_uri || "").trim();
804
+ if (redirect_uri) {
805
+ try {
806
+ const url = new URL(redirect_uri);
807
+ url.searchParams.set("error", err.oauthError);
808
+ url.searchParams.set("error_description", err.message);
809
+ const state = req.body?.state;
810
+ if (state !== undefined && state !== "") {
811
+ url.searchParams.set("state", String(state));
812
+ }
813
+ res.redirect(303, url.toString());
814
+ return;
815
+ } catch (_e) {
816
+ // fall through to default error handler
817
+ }
818
+ }
819
+ }
820
+ next(err);
821
+ });
822
+ });
823
+
824
+ app.get("/oauth/apps", requireOAuthSession, function (req, res, next) {
825
+ const session = (req as any).picoSession;
826
+ oauth
827
+ .listApps(session.rootPicoId)
828
+ .then((apps) => res.json({ apps }))
829
+ .catch(next);
830
+ });
831
+
832
+ app.post("/oauth/apps", requireOAuthSession, function (req, res, next) {
833
+ const session = (req as any).picoSession;
834
+ const body = req.body || {};
835
+ oauth
836
+ .registerApp(session.rootPicoId, {
837
+ name: body.name,
838
+ redirect_uris: body.redirect_uris,
839
+ public_client: body.public_client,
840
+ })
841
+ .then((app) => res.json(app))
842
+ .catch(next);
843
+ });
844
+
845
+ app.delete("/oauth/apps/:clientId", requireOAuthSession, function (req, res, next) {
846
+ const session = (req as any).picoSession;
847
+ oauth
848
+ .revokeApp(session.rootPicoId, req.params.clientId)
849
+ .then(() => res.json({ ok: true }))
850
+ .catch(next);
851
+ });
852
+
853
+ app.get("/oauth/channels/:eci/status", requireAuthSession, function (req, res, next) {
854
+ oauth
855
+ .channelStatusAsync(req.params.eci)
856
+ .then((status) => res.json(status))
857
+ .catch(next);
858
+ });
859
+
860
+ app.post("/oauth/channels/:eci/credentials", requireAuthSession, function (req, res, next) {
861
+ oauth
862
+ .createChannelSecret(req.params.eci)
863
+ .then((creds) => res.json(creds))
864
+ .catch(next);
865
+ });
866
+
867
+ app.delete("/oauth/channels/:eci/credentials", requireAuthSession, function (req, res, next) {
868
+ oauth
869
+ .revokeChannelSecret(req.params.eci)
870
+ .then(() => res.json({ ok: true }))
871
+ .catch(next);
872
+ });
873
+
874
+ app.delete("/oauth/channels/:eci/tokens", requireAuthSession, function (req, res, next) {
875
+ oauth
876
+ .revokeTokens(req.params.eci)
877
+ .then(() => res.json({ ok: true }))
878
+ .catch(next);
879
+ });
880
+ }