-
Notifications
You must be signed in to change notification settings - Fork 29
/
init.ts
252 lines (229 loc) · 5.83 KB
/
init.ts
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
import type { ApplicationType } from './src/index.js';
import type { types } from '@balena/pinejs';
import { sbvrUtils, errors } from '@balena/pinejs';
import express from 'express';
import _ from 'lodash';
import config from './config.js';
import packageJson from './package.json' with { type: 'json' };
import { promises as fs } from 'fs';
import { TRUST_PROXY, PORT } from './src/lib/config.js';
const getUrl = (req: express.Request) => req.url;
async function onInitModel() {
const { updateOrInsertModel } = await import(
'./src/infra/pinejs-client-helpers/index.js'
);
const appTypes = await import(
'./src/features/application-types/application-types.js'
);
const insert: types.OptionalField<ApplicationType, 'slug'> = _.cloneDeep(
appTypes.DefaultApplicationType,
);
const filter = { slug: insert.slug };
delete insert.slug;
await sbvrUtils.db.transaction(async (tx) => {
const inserted = await updateOrInsertModel(
'application_type',
filter,
insert,
tx,
);
appTypes.DefaultApplicationType.id = inserted.id;
});
}
async function onInitHooks() {
const { createAllPermissions: createAll } = await import(
'./src/infra/auth/permissions.js'
);
const auth = await import('./src/lib/auth.js');
const permissionNames = _.union(
_.flatMap(auth.ROLES),
_.flatMap(auth.KEYS, 'permissions'),
);
const { setSyncSettings } = await import('./src/features/contracts/index.js');
const { getAccessibleDeviceTypeJsons } = await import(
'./src/features/device-types/device-types.js'
);
setSyncSettings({
'hw.device-type': {
resource: 'device_type',
uniqueKey: 'slug',
includeRawContract: true,
map: {
slug: {
contractField: 'slug',
},
name: {
contractField: 'name',
},
logo: {
contractField: 'assets.logo.url',
},
is_of__cpu_architecture: {
contractField: 'data.arch',
refersTo: {
resource: 'cpu_architecture',
uniqueKey: 'slug',
},
},
device_type_alias: {
contractField: 'aliases',
isReferencedBy: {
resource: 'device_type_alias',
naturalKeyPart: 'is_referenced_by__alias',
},
},
belongs_to__device_family: {
contractField: 'data.family',
refersTo: {
resource: 'device_family',
uniqueKey: 'slug',
},
},
},
},
'hw.device-family': {
resource: 'device_family',
uniqueKey: 'slug',
map: {
slug: {
contractField: 'slug',
},
name: {
contractField: 'name',
},
is_manufactured_by__device_manufacturer: {
contractField: 'data.manufacturedBy',
refersTo: {
resource: 'device_manufacturer',
uniqueKey: 'slug',
},
},
},
},
'hw.device-manufacturer': {
resource: 'device_manufacturer',
uniqueKey: 'slug',
map: {
slug: {
contractField: 'slug',
},
name: {
contractField: 'name',
},
},
},
'arch.sw': {
resource: 'cpu_architecture',
uniqueKey: 'slug',
map: {
slug: {
contractField: 'slug',
},
},
},
});
// Pre-fetch the device types and populate the cache w/o blocking the API startup
void getAccessibleDeviceTypeJsons(sbvrUtils.api.resin);
await sbvrUtils.db.transaction((tx) =>
createAll(tx, permissionNames, auth.ROLES, auth.KEYS, {}),
);
}
async function createSuperuser() {
const { SUPERUSER_EMAIL, SUPERUSER_PASSWORD } = await import(
'./src/lib/config.js'
);
if (!SUPERUSER_EMAIL || !SUPERUSER_PASSWORD) {
return;
}
console.log('Creating superuser account...');
const { getOrInsertModelId } = await import(
'./src/infra/pinejs-client-helpers/index.js'
);
const { findUser, registerUser, updatePasswordIfNeeded } = await import(
'./src/infra/auth/auth.js'
);
const { ConflictError } = errors;
const data = {
username: 'admin',
email: SUPERUSER_EMAIL,
password: SUPERUSER_PASSWORD,
};
try {
await sbvrUtils.db.transaction(async (tx) => {
try {
await registerUser(data, tx);
console.log('Superuser created successfully!');
} catch (err) {
if (err instanceof ConflictError) {
console.log('Superuser already exists!');
const updated = await updatePasswordIfNeeded(
data.username,
SUPERUSER_PASSWORD,
tx,
);
if (updated) {
console.log('Superuser password changed.');
}
} else {
throw err;
}
}
const user = await findUser(data.username, tx);
if (user == null) {
// can't happen, but need to satisfy the compiler
return;
}
// Create the "superorg" and assign the superuser as the sole member
const organization = await getOrInsertModelId(
'organization',
{ name: user.username, handle: user.username },
tx,
);
await getOrInsertModelId(
'organization_membership',
{ user: user.id, is_member_of__organization: organization.id },
tx,
);
});
} catch (err) {
console.error('Error creating superuser:', err);
}
}
export const app = express();
app.set('trust proxy', TRUST_PROXY);
const init = async () => {
try {
const generateConfig = (process.env.GENERATE_CONFIG ?? '').trim();
if (generateConfig.length > 0) {
await fs.writeFile(generateConfig, JSON.stringify(config, null, '\t'));
process.exit();
}
const doRunTests =
(process.env.RUN_TESTS ?? '').trim() === '1'
? await import('./test/test-lib/init-tests.js')
: undefined;
// we have to load some mocks before the app starts...
if (doRunTests) {
console.log('Loading mocks...');
await doRunTests.preInit();
}
const { setup } = await import('./src/index.js');
const { startServer } = await setup(app, {
config,
version: packageJson.version,
getUrl,
onInitModel,
onInitHooks,
});
await createSuperuser();
await startServer(PORT);
if (doRunTests) {
console.log('Running tests...');
await doRunTests.postInit();
}
} catch (err) {
console.error('Failed to initialize:', err);
process.exit(1);
}
};
void init();