forked from panva/node-oidc-provider
-
Notifications
You must be signed in to change notification settings - Fork 0
/
standalone.js
82 lines (69 loc) · 2.19 KB
/
standalone.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/* eslint-disable no-console */
import * as path from 'node:path';
import { promisify } from 'node:util';
import { dirname } from 'desm';
import render from '@koa/ejs';
import helmet from 'helmet';
import Provider from '../lib/index.js'; // from 'oidc-provider';
import Account from './support/account.js';
import configuration from './support/configuration.js';
import routes from './routes/koa.js';
const __dirname = dirname(import.meta.url);
const { PORT = 3000, ISSUER = `http://localhost:${PORT}` } = process.env;
configuration.findAccount = Account.findAccount;
let server;
try {
let adapter;
if (process.env.MONGODB_URI) {
({ default: adapter } = await import('./adapters/mongodb.js'));
await adapter.connect();
}
const prod = process.env.NODE_ENV === 'production';
const provider = new Provider(ISSUER, { adapter, ...configuration });
const directives = helmet.contentSecurityPolicy.getDefaultDirectives();
delete directives['form-action'];
const pHelmet = promisify(helmet({
contentSecurityPolicy: {
useDefaults: false,
directives,
},
}));
provider.use(async (ctx, next) => {
const origSecure = ctx.req.secure;
ctx.req.secure = ctx.request.secure;
await pHelmet(ctx.req, ctx.res);
ctx.req.secure = origSecure;
return next();
});
if (prod) {
provider.proxy = true;
provider.use(async (ctx, next) => {
if (ctx.secure) {
await next();
} else if (ctx.method === 'GET' || ctx.method === 'HEAD') {
ctx.status = 303;
ctx.redirect(ctx.href.replace(/^http:\/\//i, 'https://'));
} else {
ctx.body = {
error: 'invalid_request',
error_description: 'do yourself a favor and only use https',
};
ctx.status = 400;
}
});
}
render(provider.app, {
cache: false,
viewExt: 'ejs',
layout: '_layout',
root: path.join(__dirname, 'views'),
});
provider.use(routes(provider).routes());
server = provider.listen(PORT, () => {
console.log(`application is listening on port ${PORT}, check its /.well-known/openid-configuration`);
});
} catch (err) {
if (server?.listening) server.close();
console.error(err);
process.exitCode = 1;
}