-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathindex.ts
More file actions
231 lines (214 loc) · 7.52 KB
/
Copy pathindex.ts
File metadata and controls
231 lines (214 loc) · 7.52 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
import simplifyPlugin from "@graphile-contrib/pg-simplify-inflector";
import PgPubsub from "@graphile/pg-pubsub";
import crypto from "crypto";
import express from "express";
import { graphqlUploadExpress } from "graphql-upload-ts";
import {
makePluginHook,
postgraphile,
PostGraphileOptions,
} from "postgraphile";
import { migrate, MigrateDBConfig } from "postgres-migrations";
import config from "./config";
import createTasKPlugin from "./plugins/createTask";
import importCtfPlugin from "./plugins/importCtf";
import uploadLogoPlugin from "./plugins/uploadLogo";
import uploadScalar from "./plugins/uploadScalar";
import ldapAuthPlugin from "./plugins/ldapAuth";
import localAuthControlPlugin from "./plugins/localAuthControl";
import { Pool } from "pg";
import { icalRoute } from "./routes/ical";
import ConnectionFilterPlugin from "postgraphile-plugin-connection-filter";
import OperationHook from "@graphile/operation-hooks";
import discordHooks from "./discord/hooks";
import { initDiscordBot } from "./discord";
import PgManyToManyPlugin from "@graphile-contrib/pg-many-to-many";
import ProfileSubscriptionPlugin from "./plugins/ProfileSubscriptionPlugin";
function getDbUrl(role: "user" | "admin") {
const login = config.db[role].login;
const password = config.db[role].password;
return `postgres://${login}:${password}@${config.db.host}:${config.db.port}/${config.db.database}`;
}
function createOptions() {
let secret: string;
if (config.sessionSecret.length < 64 && config.env !== "development") {
console.info(
"Using random session secret since SESSION_SECRET is too short. All users will be logged out."
);
secret = crypto.randomBytes(32).toString("hex");
} else {
secret = config.sessionSecret;
}
const postgraphileOptions: PostGraphileOptions = {
pluginHook: makePluginHook([PgPubsub, OperationHook]),
subscriptions: true,
dynamicJson: true,
simpleSubscriptions: true,
setofFunctionsContainNulls: false,
ignoreRBAC: false,
disableQueryLog: true,
ignoreIndexes: false,
subscriptionAuthorizationFunction: "ctfnote_private.validate_subscription",
jwtPgTypeIdentifier: "ctfnote.jwt",
pgDefaultRole: "user_anonymous",
jwtSecret: secret,
appendPlugins: [
simplifyPlugin,
uploadScalar,
importCtfPlugin,
uploadLogoPlugin,
createTasKPlugin,
ConnectionFilterPlugin,
discordHooks,
PgManyToManyPlugin,
ProfileSubscriptionPlugin,
ldapAuthPlugin,
...localAuthControlPlugin,
],
ownerConnectionString: getDbUrl("admin"),
enableQueryBatching: true,
legacyRelations: "omit" as const,
};
if (config.env == "development") {
postgraphileOptions.watchPg = true;
postgraphileOptions.disableQueryLog = false;
postgraphileOptions.graphiql = true;
postgraphileOptions.exportGqlSchemaPath = "schema.graphql";
postgraphileOptions.retryOnInitFail = true;
postgraphileOptions.enhanceGraphiql = true;
postgraphileOptions.allowExplain = true;
postgraphileOptions.jwtSecret = "DEV";
postgraphileOptions.showErrorStack = "json" as const;
postgraphileOptions.extendedErrors = [
"severity",
"code",
"detail",
"hint",
"position",
"internalPosition",
"internalQuery",
"where",
"schema",
"table",
"column",
"dataType",
"constraint",
"file",
"line",
"routine",
];
postgraphileOptions.graphileBuildOptions = {
connectionFilterAllowedOperators: ["includesInsensitive"],
connectionFilterAllowedFieldTypes: ["String"],
connectionFilterComputedColumns: false,
connectionFilterSetofFunctions: false,
connectionFilterArrays: false,
};
}
return postgraphileOptions;
}
function createApp(postgraphileOptions: PostGraphileOptions) {
const pool = new Pool({
connectionString: getDbUrl("user"),
});
const app = express();
app.use(graphqlUploadExpress());
app.use(
"/uploads",
express.static("uploads", {
setHeaders: function (res) {
res.set("Content-Disposition", "attachment");
},
})
);
app.use(postgraphile(pool, "ctfnote", postgraphileOptions));
app.use("/calendar.ics", icalRoute(pool));
return app;
}
async function performMigrations() {
const dbConfig: MigrateDBConfig = {
database: config.db.database,
user: config.db.admin.login,
password: config.db.admin.password,
host: config.db.host,
port: config.db.port,
ensureDatabaseExists: true,
defaultDatabase: "postgres",
};
await migrate(dbConfig, "./migrations");
}
function validateAuthConfiguration() {
// Check if at least one authentication method is enabled
if (!config.localAuthEnabled && !config.ldap.enabled) {
console.error(
"┌──────────────────────────────────────────────────────────────────┐"
);
console.error(
"│ ⚠️ CRITICAL WARNING ⚠️ │"
);
console.error(
"├──────────────────────────────────────────────────────────────────┤"
);
console.error(
"│ Both LOCAL_AUTH_ENABLED and LDAP_ENABLED are set to false! │"
);
console.error(
"│ This instance is misconfigured and users cannot authenticate. │"
);
console.error(
"│ │"
);
console.error(
"│ Please enable at least one authentication method: │"
);
console.error(
"│ - Set LOCAL_AUTH_ENABLED=true for local authentication │"
);
console.error(
"│ - Set LDAP_ENABLED=true for LDAP authentication │"
);
console.error(
"│ │"
);
console.error(
"│ The server will continue running but authentication will fail. │"
);
console.error(
"└──────────────────────────────────────────────────────────────────┘"
);
// In production, we should consider exiting
if (config.env === "production") {
console.error(
"\n❌ Exiting due to misconfiguration in production environment."
);
process.exit(1);
}
} else if (!config.localAuthEnabled && config.ldap.enabled) {
console.info(
"ℹ️ Local authentication is disabled. Only LDAP authentication is available."
);
} else if (config.localAuthEnabled && !config.ldap.enabled) {
console.info(
"ℹ️ LDAP authentication is disabled. Only local authentication is available."
);
} else {
console.info("✅ Both local and LDAP authentication methods are enabled.");
}
}
async function main() {
await performMigrations();
if (config.db.migrateOnly) {
console.log("Migrations done. Exiting.");
return;
}
// Validate authentication configuration before starting the server
validateAuthConfiguration();
const postgraphileOptions = createOptions();
const app = createApp(postgraphileOptions);
await initDiscordBot();
app.listen(config.web.port, () => {
//sendMessageToDiscord("CTFNote API started");
console.log(`Listening on :${config.web.port}`);
});
}
main();