3.0.0.mjs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  1. import { v4 as uuid } from 'uuid'
  2. import bcrypt from 'bcryptjs'
  3. import crypto from 'node:crypto'
  4. import { DateTime } from 'luxon'
  5. import { pem2jwk } from 'pem-jwk'
  6. export async function up (knex) {
  7. WIKI.logger.info('Running 3.0.0 database migration...')
  8. // =====================================
  9. // PG EXTENSIONS
  10. // =====================================
  11. await knex.raw('CREATE EXTENSION IF NOT EXISTS ltree;')
  12. await knex.raw('CREATE EXTENSION IF NOT EXISTS pgcrypto;')
  13. await knex.raw('CREATE EXTENSION IF NOT EXISTS pg_trgm;')
  14. await knex.schema
  15. // =====================================
  16. // MODEL TABLES
  17. // =====================================
  18. // ACTIVITY LOGS -----------------------
  19. .createTable('activityLogs', table => {
  20. table.uuid('id').notNullable().primary().defaultTo(knex.raw('gen_random_uuid()'))
  21. table.timestamp('ts').notNullable().defaultTo(knex.fn.now())
  22. table.string('action').notNullable()
  23. table.jsonb('meta').notNullable()
  24. })
  25. // ANALYTICS ---------------------------
  26. .createTable('analytics', table => {
  27. table.uuid('id').notNullable().primary().defaultTo(knex.raw('gen_random_uuid()'))
  28. table.string('module').notNullable()
  29. table.boolean('isEnabled').notNullable().defaultTo(false)
  30. table.jsonb('config').notNullable()
  31. })
  32. // API KEYS ----------------------------
  33. .createTable('apiKeys', table => {
  34. table.uuid('id').notNullable().primary().defaultTo(knex.raw('gen_random_uuid()'))
  35. table.string('name').notNullable()
  36. table.text('key').notNullable()
  37. table.timestamp('expiration').notNullable().defaultTo(knex.fn.now())
  38. table.boolean('isRevoked').notNullable().defaultTo(false)
  39. table.timestamp('createdAt').notNullable().defaultTo(knex.fn.now())
  40. table.timestamp('updatedAt').notNullable().defaultTo(knex.fn.now())
  41. })
  42. // ASSETS ------------------------------
  43. .createTable('assets', table => {
  44. table.uuid('id').notNullable().primary().defaultTo(knex.raw('gen_random_uuid()'))
  45. table.string('fileName').notNullable()
  46. table.string('fileExt').notNullable()
  47. table.boolean('isSystem').notNullable().defaultTo(false)
  48. table.enum('kind', ['document', 'image', 'other']).notNullable().defaultTo('other')
  49. table.string('mimeType').notNullable().defaultTo('application/octet-stream')
  50. table.integer('fileSize').unsigned().comment('In bytes')
  51. table.jsonb('meta').notNullable().defaultTo('{}')
  52. table.timestamp('createdAt').notNullable().defaultTo(knex.fn.now())
  53. table.timestamp('updatedAt').notNullable().defaultTo(knex.fn.now())
  54. table.binary('data')
  55. table.binary('preview')
  56. table.enum('previewState', ['none', 'pending', 'ready', 'failed']).notNullable().defaultTo('none')
  57. table.jsonb('storageInfo')
  58. })
  59. // AUTHENTICATION ----------------------
  60. .createTable('authentication', table => {
  61. table.uuid('id').notNullable().primary().defaultTo(knex.raw('gen_random_uuid()'))
  62. table.string('module').notNullable()
  63. table.boolean('isEnabled').notNullable().defaultTo(false)
  64. table.string('displayName').notNullable().defaultTo('')
  65. table.jsonb('config').notNullable().defaultTo('{}')
  66. table.boolean('selfRegistration').notNullable().defaultTo(false)
  67. table.string('allowedEmailRegex')
  68. table.specificType('autoEnrollGroups', 'uuid[]')
  69. })
  70. .createTable('blocks', table => {
  71. table.uuid('id').notNullable().primary().defaultTo(knex.raw('gen_random_uuid()'))
  72. table.string('block').notNullable()
  73. table.string('name').notNullable()
  74. table.string('description').notNullable()
  75. table.string('icon')
  76. table.boolean('isEnabled').notNullable().defaultTo(false)
  77. table.boolean('isCustom').notNullable().defaultTo(false)
  78. table.json('config').notNullable()
  79. })
  80. // COMMENT PROVIDERS -------------------
  81. .createTable('commentProviders', table => {
  82. table.uuid('id').notNullable().primary().defaultTo(knex.raw('gen_random_uuid()'))
  83. table.string('module').notNullable()
  84. table.boolean('isEnabled').notNullable().defaultTo(false)
  85. table.json('config').notNullable()
  86. })
  87. // COMMENTS ----------------------------
  88. .createTable('comments', table => {
  89. table.uuid('id').notNullable().primary().defaultTo(knex.raw('gen_random_uuid()'))
  90. table.uuid('replyTo')
  91. table.text('content').notNullable()
  92. table.text('render').notNullable().defaultTo('')
  93. table.string('name').notNullable().defaultTo('')
  94. table.string('email').notNullable().defaultTo('')
  95. table.string('ip').notNullable().defaultTo('')
  96. table.timestamp('createdAt').notNullable().defaultTo(knex.fn.now())
  97. table.timestamp('updatedAt').notNullable().defaultTo(knex.fn.now())
  98. })
  99. // GROUPS ------------------------------
  100. .createTable('groups', table => {
  101. table.uuid('id').notNullable().primary().defaultTo(knex.raw('gen_random_uuid()'))
  102. table.string('name').notNullable()
  103. table.jsonb('permissions').notNullable()
  104. table.jsonb('rules').notNullable()
  105. table.string('redirectOnLogin').notNullable().defaultTo('')
  106. table.string('redirectOnFirstLogin').notNullable().defaultTo('')
  107. table.string('redirectOnLogout').notNullable().defaultTo('')
  108. table.boolean('isSystem').notNullable().defaultTo(false)
  109. table.timestamp('createdAt').notNullable().defaultTo(knex.fn.now())
  110. table.timestamp('updatedAt').notNullable().defaultTo(knex.fn.now())
  111. })
  112. // HOOKS -------------------------------
  113. .createTable('hooks', table => {
  114. table.uuid('id').notNullable().primary().defaultTo(knex.raw('gen_random_uuid()'))
  115. table.string('name').notNullable()
  116. table.jsonb('events').notNullable().defaultTo('[]')
  117. table.string('url').notNullable()
  118. table.boolean('includeMetadata').notNullable().defaultTo(false)
  119. table.boolean('includeContent').notNullable().defaultTo(false)
  120. table.boolean('acceptUntrusted').notNullable().defaultTo(false)
  121. table.string('authHeader')
  122. table.enum('state', ['pending', 'error', 'success']).notNullable().defaultTo('pending')
  123. table.string('lastErrorMessage')
  124. table.timestamp('createdAt').notNullable().defaultTo(knex.fn.now())
  125. table.timestamp('updatedAt').notNullable().defaultTo(knex.fn.now())
  126. })
  127. // JOB HISTORY -------------------------
  128. .createTable('jobHistory', table => {
  129. table.uuid('id').notNullable().primary()
  130. table.string('task').notNullable()
  131. table.enum('state', ['active', 'completed', 'failed', 'interrupted']).notNullable()
  132. table.boolean('useWorker').notNullable().defaultTo(false)
  133. table.boolean('wasScheduled').notNullable().defaultTo(false)
  134. table.jsonb('payload')
  135. table.integer('attempt').notNullable().defaultTo(1)
  136. table.integer('maxRetries').notNullable().defaultTo(0)
  137. table.text('lastErrorMessage')
  138. table.string('executedBy')
  139. table.timestamp('createdAt').notNullable()
  140. table.timestamp('startedAt').notNullable().defaultTo(knex.fn.now())
  141. table.timestamp('completedAt')
  142. })
  143. // JOB SCHEDULE ------------------------
  144. .createTable('jobSchedule', table => {
  145. table.uuid('id').notNullable().primary().defaultTo(knex.raw('gen_random_uuid()'))
  146. table.string('task').notNullable()
  147. table.string('cron').notNullable()
  148. table.string('type').notNullable().defaultTo('system')
  149. table.jsonb('payload')
  150. table.timestamp('createdAt').notNullable().defaultTo(knex.fn.now())
  151. table.timestamp('updatedAt').notNullable().defaultTo(knex.fn.now())
  152. })
  153. // JOB SCHEDULE ------------------------
  154. .createTable('jobLock', table => {
  155. table.string('key').notNullable().primary()
  156. table.string('lastCheckedBy')
  157. table.timestamp('lastCheckedAt').notNullable().defaultTo(knex.fn.now())
  158. })
  159. // JOBS --------------------------------
  160. .createTable('jobs', table => {
  161. table.uuid('id').notNullable().primary().defaultTo(knex.raw('gen_random_uuid()'))
  162. table.string('task').notNullable()
  163. table.boolean('useWorker').notNullable().defaultTo(false)
  164. table.jsonb('payload')
  165. table.integer('retries').notNullable().defaultTo(0)
  166. table.integer('maxRetries').notNullable().defaultTo(0)
  167. table.timestamp('waitUntil')
  168. table.boolean('isScheduled').notNullable().defaultTo(false)
  169. table.string('createdBy')
  170. table.timestamp('createdAt').notNullable().defaultTo(knex.fn.now())
  171. table.timestamp('updatedAt').notNullable().defaultTo(knex.fn.now())
  172. })
  173. // LOCALES -----------------------------
  174. .createTable('locales', table => {
  175. table.string('code', 10).notNullable().primary()
  176. table.string('name').notNullable()
  177. table.string('nativeName').notNullable()
  178. table.string('language', 2).notNullable().index()
  179. table.string('region', 2)
  180. table.string('script', 4)
  181. table.boolean('isRTL').notNullable().defaultTo(false)
  182. table.jsonb('strings')
  183. table.integer('completeness').notNullable().defaultTo(0)
  184. table.timestamp('createdAt').notNullable().defaultTo(knex.fn.now())
  185. table.timestamp('updatedAt').notNullable().defaultTo(knex.fn.now())
  186. })
  187. // NAVIGATION ----------------------------
  188. .createTable('navigation', table => {
  189. table.uuid('id').notNullable().primary().defaultTo(knex.raw('gen_random_uuid()'))
  190. table.jsonb('items').notNullable().defaultTo('[]')
  191. })
  192. // PAGE HISTORY ------------------------
  193. .createTable('pageHistory', table => {
  194. table.uuid('id').notNullable().primary().defaultTo(knex.raw('gen_random_uuid()'))
  195. table.uuid('pageId').notNullable().index()
  196. table.string('action').defaultTo('updated')
  197. table.string('reason')
  198. table.jsonb('affectedFields').notNullable().defaultTo('[]')
  199. table.string('locale', 10).notNullable().defaultTo('en')
  200. table.string('path').notNullable()
  201. table.string('hash').notNullable()
  202. table.string('alias')
  203. table.string('title').notNullable()
  204. table.string('description')
  205. table.string('icon')
  206. table.enu('publishState', ['draft', 'published', 'scheduled']).notNullable().defaultTo('draft')
  207. table.timestamp('publishStartDate')
  208. table.timestamp('publishEndDate')
  209. table.jsonb('config').notNullable().defaultTo('{}')
  210. table.jsonb('relations').notNullable().defaultTo('[]')
  211. table.text('content')
  212. table.text('render')
  213. table.jsonb('toc')
  214. table.string('editor').notNullable()
  215. table.string('contentType').notNullable()
  216. table.jsonb('scripts').notNullable().defaultTo('{}')
  217. table.timestamp('createdAt').notNullable().defaultTo(knex.fn.now())
  218. table.timestamp('versionDate').notNullable().defaultTo(knex.fn.now())
  219. })
  220. // PAGE LINKS --------------------------
  221. .createTable('pageLinks', table => {
  222. table.increments('id').primary()
  223. table.string('path').notNullable()
  224. table.string('locale', 10).notNullable()
  225. })
  226. // PAGES -------------------------------
  227. .createTable('pages', table => {
  228. table.uuid('id').notNullable().primary().defaultTo(knex.raw('gen_random_uuid()'))
  229. table.string('locale', 10).notNullable()
  230. table.string('path').notNullable()
  231. table.string('hash').notNullable()
  232. table.string('alias')
  233. table.string('title').notNullable()
  234. table.string('description')
  235. table.string('icon')
  236. table.enu('publishState', ['draft', 'published', 'scheduled']).notNullable().defaultTo('draft')
  237. table.timestamp('publishStartDate')
  238. table.timestamp('publishEndDate')
  239. table.jsonb('config').notNullable().defaultTo('{}')
  240. table.jsonb('relations').notNullable().defaultTo('[]')
  241. table.text('content')
  242. table.text('render')
  243. table.text('searchContent')
  244. table.specificType('ts', 'tsvector').index('pages_ts_idx', { indexType: 'GIN' })
  245. table.specificType('tags', 'text[]').index('pages_tags_idx', { indexType: 'GIN' })
  246. table.jsonb('toc')
  247. table.string('editor').notNullable()
  248. table.string('contentType').notNullable()
  249. table.boolean('isBrowsable').notNullable().defaultTo(true)
  250. table.boolean('isSearchable').notNullable().defaultTo(true)
  251. table.specificType('isSearchableComputed', `boolean GENERATED ALWAYS AS ("publishState" != 'draft' AND "isSearchable") STORED`).index()
  252. table.string('password')
  253. table.integer('ratingScore').notNullable().defaultTo(0)
  254. table.integer('ratingCount').notNullable().defaultTo(0)
  255. table.jsonb('scripts').notNullable().defaultTo('{}')
  256. table.jsonb('historyData').notNullable().defaultTo('{}')
  257. table.timestamp('createdAt').notNullable().defaultTo(knex.fn.now())
  258. table.timestamp('updatedAt').notNullable().defaultTo(knex.fn.now())
  259. })
  260. // RENDERERS ---------------------------
  261. .createTable('renderers', table => {
  262. table.uuid('id').notNullable().primary().defaultTo(knex.raw('gen_random_uuid()'))
  263. table.string('module').notNullable()
  264. table.boolean('isEnabled').notNullable().defaultTo(false)
  265. table.jsonb('config').notNullable().defaultTo('{}')
  266. })
  267. // SETTINGS ----------------------------
  268. .createTable('settings', table => {
  269. table.string('key').notNullable().primary()
  270. table.jsonb('value')
  271. })
  272. // SITES -------------------------------
  273. .createTable('sites', table => {
  274. table.uuid('id').notNullable().primary().defaultTo(knex.raw('gen_random_uuid()'))
  275. table.string('hostname').notNullable()
  276. table.boolean('isEnabled').notNullable().defaultTo(false)
  277. table.jsonb('config').notNullable()
  278. table.timestamp('createdAt').notNullable().defaultTo(knex.fn.now())
  279. })
  280. // STORAGE -----------------------------
  281. .createTable('storage', table => {
  282. table.uuid('id').notNullable().primary().defaultTo(knex.raw('gen_random_uuid()'))
  283. table.string('module').notNullable()
  284. table.boolean('isEnabled').notNullable().defaultTo(false)
  285. table.jsonb('contentTypes')
  286. table.jsonb('assetDelivery')
  287. table.jsonb('versioning')
  288. table.jsonb('schedule')
  289. table.jsonb('config')
  290. table.jsonb('state')
  291. })
  292. // TAGS --------------------------------
  293. .createTable('tags', table => {
  294. table.uuid('id').notNullable().primary().defaultTo(knex.raw('gen_random_uuid()'))
  295. table.string('tag').notNullable()
  296. table.integer('usageCount').notNullable().defaultTo(0)
  297. table.timestamp('createdAt').notNullable().defaultTo(knex.fn.now())
  298. table.timestamp('updatedAt').notNullable().defaultTo(knex.fn.now())
  299. })
  300. // TREE --------------------------------
  301. .createTable('tree', table => {
  302. table.uuid('id').notNullable().primary().defaultTo(knex.raw('gen_random_uuid()'))
  303. table.specificType('folderPath', 'ltree').index().index('tree_folderpath_gist_idx', { indexType: 'GIST' })
  304. table.string('fileName').notNullable().index()
  305. table.string('hash').notNullable().index()
  306. table.enu('type', ['folder', 'page', 'asset']).notNullable().index()
  307. table.string('locale', 10).notNullable().defaultTo('en').index()
  308. table.string('title').notNullable()
  309. table.enum('navigationMode', ['inherit', 'override', 'overrideExact', 'hide', 'hideExact']).notNullable().defaultTo('inherit').index()
  310. table.uuid('navigationId').index()
  311. table.specificType('tags', 'text[]').index('tree_tags_idx', { indexType: 'GIN' })
  312. table.jsonb('meta').notNullable().defaultTo('{}')
  313. table.timestamp('createdAt').notNullable().defaultTo(knex.fn.now())
  314. table.timestamp('updatedAt').notNullable().defaultTo(knex.fn.now())
  315. })
  316. // USER AVATARS ------------------------
  317. .createTable('userAvatars', table => {
  318. table.uuid('id').notNullable().primary()
  319. table.binary('data').notNullable()
  320. })
  321. // USER EDITOR SETTINGS ----------------
  322. .createTable('userEditorSettings', table => {
  323. table.uuid('id').notNullable()
  324. table.string('editor').notNullable()
  325. table.jsonb('config').notNullable().defaultTo('{}')
  326. table.primary(['id', 'editor'])
  327. })
  328. // USER KEYS ---------------------------
  329. .createTable('userKeys', table => {
  330. table.uuid('id').notNullable().primary().defaultTo(knex.raw('gen_random_uuid()'))
  331. table.string('kind').notNullable()
  332. table.string('token').notNullable()
  333. table.jsonb('meta').notNullable().defaultTo('{}')
  334. table.timestamp('validUntil').notNullable()
  335. table.timestamp('createdAt').notNullable().defaultTo(knex.fn.now())
  336. })
  337. // USERS -------------------------------
  338. .createTable('users', table => {
  339. table.uuid('id').notNullable().primary().defaultTo(knex.raw('gen_random_uuid()'))
  340. table.string('email').notNullable()
  341. table.string('name').notNullable()
  342. table.jsonb('auth').notNullable().defaultTo('{}')
  343. table.jsonb('meta').notNullable().defaultTo('{}')
  344. table.jsonb('prefs').notNullable().defaultTo('{}')
  345. table.boolean('hasAvatar').notNullable().defaultTo(false)
  346. table.boolean('isSystem').notNullable().defaultTo(false)
  347. table.boolean('isActive').notNullable().defaultTo(false)
  348. table.boolean('isVerified').notNullable().defaultTo(false)
  349. table.timestamp('lastLoginAt').index()
  350. table.timestamp('createdAt').notNullable().defaultTo(knex.fn.now())
  351. table.timestamp('updatedAt').notNullable().defaultTo(knex.fn.now())
  352. })
  353. // =====================================
  354. // RELATION TABLES
  355. // =====================================
  356. // USER GROUPS -------------------------
  357. .createTable('userGroups', table => {
  358. table.increments('id').primary()
  359. table.uuid('userId').references('id').inTable('users').onDelete('CASCADE')
  360. table.uuid('groupId').references('id').inTable('groups').onDelete('CASCADE')
  361. })
  362. // =====================================
  363. // REFERENCES
  364. // =====================================
  365. .table('activityLogs', table => {
  366. table.uuid('userId').notNullable().references('id').inTable('users')
  367. })
  368. .table('analytics', table => {
  369. table.uuid('siteId').notNullable().references('id').inTable('sites')
  370. })
  371. .table('assets', table => {
  372. table.uuid('authorId').notNullable().references('id').inTable('users')
  373. table.uuid('siteId').notNullable().references('id').inTable('sites').index()
  374. })
  375. .table('blocks', table => {
  376. table.uuid('siteId').notNullable().references('id').inTable('sites')
  377. })
  378. .table('commentProviders', table => {
  379. table.uuid('siteId').notNullable().references('id').inTable('sites')
  380. })
  381. .table('comments', table => {
  382. table.uuid('pageId').notNullable().references('id').inTable('pages').index()
  383. table.uuid('authorId').notNullable().references('id').inTable('users').index()
  384. })
  385. .table('navigation', table => {
  386. table.uuid('siteId').notNullable().references('id').inTable('sites').index()
  387. })
  388. .table('pageHistory', table => {
  389. table.uuid('authorId').notNullable().references('id').inTable('users')
  390. table.uuid('siteId').notNullable().references('id').inTable('sites').index()
  391. })
  392. .table('pageLinks', table => {
  393. table.uuid('pageId').notNullable().references('id').inTable('pages').onDelete('CASCADE')
  394. table.index(['path', 'locale'])
  395. })
  396. .table('pages', table => {
  397. table.uuid('authorId').notNullable().references('id').inTable('users').index()
  398. table.uuid('creatorId').notNullable().references('id').inTable('users').index()
  399. table.uuid('ownerId').notNullable().references('id').inTable('users').index()
  400. table.uuid('siteId').notNullable().references('id').inTable('sites').index()
  401. })
  402. .table('storage', table => {
  403. table.uuid('siteId').notNullable().references('id').inTable('sites')
  404. })
  405. .table('tags', table => {
  406. table.uuid('siteId').notNullable().references('id').inTable('sites')
  407. table.unique(['siteId', 'tag'])
  408. })
  409. .table('tree', table => {
  410. table.uuid('siteId').notNullable().references('id').inTable('sites')
  411. })
  412. .table('userKeys', table => {
  413. table.uuid('userId').notNullable().references('id').inTable('users')
  414. })
  415. // =====================================
  416. // TS WORD SUGGESTION TABLE
  417. // =====================================
  418. .createTable('autocomplete', table => {
  419. table.text('word')
  420. })
  421. .raw(`CREATE INDEX "autocomplete_idx" ON "autocomplete" USING GIN (word gin_trgm_ops)`)
  422. // =====================================
  423. // DEFAULT DATA
  424. // =====================================
  425. // -> GENERATE IDS
  426. const groupAdminId = uuid()
  427. const groupUserId = uuid()
  428. const groupGuestId = '10000000-0000-4000-8000-000000000001'
  429. const siteId = uuid()
  430. const authModuleId = uuid()
  431. const userAdminId = uuid()
  432. const userGuestId = uuid()
  433. // -> SYSTEM CONFIG
  434. WIKI.logger.info('Generating certificates...')
  435. const secret = crypto.randomBytes(32).toString('hex')
  436. const certs = crypto.generateKeyPairSync('rsa', {
  437. modulusLength: 2048,
  438. publicKeyEncoding: {
  439. type: 'pkcs1',
  440. format: 'pem'
  441. },
  442. privateKeyEncoding: {
  443. type: 'pkcs1',
  444. format: 'pem',
  445. cipher: 'aes-256-cbc',
  446. passphrase: secret
  447. }
  448. })
  449. await knex('settings').insert([
  450. {
  451. key: 'auth',
  452. value: {
  453. audience: 'urn:wiki.js',
  454. tokenExpiration: '30m',
  455. tokenRenewal: '14d',
  456. certs: {
  457. jwk: pem2jwk(certs.publicKey),
  458. public: certs.publicKey,
  459. private: certs.privateKey
  460. },
  461. secret,
  462. rootAdminUserId: userAdminId,
  463. guestUserId: userGuestId
  464. }
  465. },
  466. {
  467. key: 'flags',
  468. value: {
  469. experimental: false,
  470. authDebug: false,
  471. sqlLog: false
  472. }
  473. },
  474. {
  475. key: 'icons',
  476. value: {
  477. fa: {
  478. isActive: true,
  479. config: {
  480. version: 6,
  481. license: 'free',
  482. token: ''
  483. }
  484. },
  485. la: {
  486. isActive: true
  487. }
  488. }
  489. },
  490. {
  491. key: 'mail',
  492. value: {
  493. senderName: '',
  494. senderEmail: '',
  495. host: '',
  496. port: 465,
  497. name: '',
  498. secure: true,
  499. verifySSL: true,
  500. user: '',
  501. pass: '',
  502. useDKIM: false,
  503. dkimDomainName: '',
  504. dkimKeySelector: '',
  505. dkimPrivateKey: ''
  506. }
  507. },
  508. {
  509. key: 'search',
  510. value: {
  511. termHighlighting: true,
  512. dictOverrides: {}
  513. }
  514. },
  515. {
  516. key: 'security',
  517. value: {
  518. corsConfig: '',
  519. corsMode: 'OFF',
  520. cspDirectives: '',
  521. disallowFloc: true,
  522. disallowIframe: true,
  523. disallowOpenRedirect: true,
  524. enforceCsp: false,
  525. enforceHsts: false,
  526. enforceSameOriginReferrerPolicy: true,
  527. forceAssetDownload: true,
  528. hstsDuration: 0,
  529. trustProxy: false,
  530. authJwtAudience: 'urn:wiki.js',
  531. authJwtExpiration: '30m',
  532. authJwtRenewablePeriod: '14d',
  533. uploadMaxFileSize: 10485760,
  534. uploadMaxFiles: 20,
  535. uploadScanSVG: true
  536. }
  537. },
  538. {
  539. key: 'update',
  540. value: {
  541. lastCheckedAt: null,
  542. version: WIKI.version,
  543. versionDate: WIKI.releaseDate
  544. }
  545. },
  546. {
  547. key: 'userDefaults',
  548. value: {
  549. timezone: 'America/New_York',
  550. dateFormat: 'YYYY-MM-DD',
  551. timeFormat: '12h'
  552. }
  553. }
  554. ])
  555. // -> DEFAULT SITE
  556. await knex('sites').insert({
  557. id: siteId,
  558. hostname: '*',
  559. isEnabled: true,
  560. config: {
  561. title: 'My Wiki Site',
  562. description: '',
  563. company: '',
  564. contentLicense: '',
  565. footerExtra: '',
  566. pageExtensions: ['md', 'html', 'txt'],
  567. pageCasing: true,
  568. discoverable: false,
  569. defaults: {
  570. tocDepth: {
  571. min: 1,
  572. max: 2
  573. }
  574. },
  575. features: {
  576. browse: true,
  577. ratings: false,
  578. ratingsMode: 'off',
  579. comments: false,
  580. contributions: false,
  581. profile: true,
  582. reasonForChange: 'required',
  583. search: true
  584. },
  585. logoText: true,
  586. sitemap: true,
  587. robots: {
  588. index: true,
  589. follow: true
  590. },
  591. authStrategies: [{ id: authModuleId, order: 0, isVisible: true }],
  592. locales: {
  593. primary: 'en',
  594. active: ['en']
  595. },
  596. assets: {
  597. logo: false,
  598. logoExt: 'svg',
  599. favicon: false,
  600. faviconExt: 'svg',
  601. loginBg: false
  602. },
  603. editors: {
  604. asciidoc: {
  605. isActive: true,
  606. config: {}
  607. },
  608. markdown: {
  609. isActive: true,
  610. config: {
  611. allowHTML: true,
  612. kroki: false,
  613. krokiServerUrl: 'https://kroki.io',
  614. latexEngine: 'katex',
  615. lineBreaks: true,
  616. linkify: true,
  617. multimdTable: true,
  618. plantuml: false,
  619. plantumlServerUrl: 'https://www.plantuml.com/plantuml/',
  620. quotes: 'english',
  621. tabWidth: 2,
  622. typographer: false,
  623. underline: true
  624. }
  625. },
  626. wysiwyg: {
  627. isActive: true,
  628. config: {}
  629. }
  630. },
  631. theme: {
  632. dark: false,
  633. codeBlocksTheme: 'github-dark',
  634. colorPrimary: '#1976D2',
  635. colorSecondary: '#02C39A',
  636. colorAccent: '#FF9800',
  637. colorHeader: '#000000',
  638. colorSidebar: '#1976D2',
  639. injectCSS: '',
  640. injectHead: '',
  641. injectBody: '',
  642. contentWidth: 'full',
  643. sidebarPosition: 'left',
  644. tocPosition: 'right',
  645. showSharingMenu: true,
  646. showPrintBtn: true,
  647. baseFont: 'roboto',
  648. contentFont: 'roboto'
  649. },
  650. uploads: {
  651. conflictBehavior: 'overwrite',
  652. normalizeFilename: true
  653. }
  654. }
  655. })
  656. // -> DEFAULT GROUPS
  657. await knex('groups').insert([
  658. {
  659. id: groupAdminId,
  660. name: 'Administrators',
  661. permissions: JSON.stringify(['manage:system']),
  662. rules: JSON.stringify([]),
  663. isSystem: true
  664. },
  665. {
  666. id: groupUserId,
  667. name: 'Users',
  668. permissions: JSON.stringify(['read:pages', 'read:assets', 'read:comments']),
  669. rules: JSON.stringify([
  670. {
  671. id: uuid(),
  672. name: 'Default Rule',
  673. roles: ['read:pages', 'read:assets', 'read:comments'],
  674. match: 'START',
  675. mode: 'ALLOW',
  676. path: '',
  677. locales: [],
  678. sites: []
  679. }
  680. ]),
  681. isSystem: true
  682. },
  683. {
  684. id: groupGuestId,
  685. name: 'Guests',
  686. permissions: JSON.stringify(['read:pages', 'read:assets', 'read:comments']),
  687. rules: JSON.stringify([
  688. {
  689. id: uuid(),
  690. name: 'Default Rule',
  691. roles: ['read:pages', 'read:assets', 'read:comments'],
  692. match: 'START',
  693. mode: 'DENY',
  694. path: '',
  695. locales: [],
  696. sites: []
  697. }
  698. ]),
  699. isSystem: true
  700. }
  701. ])
  702. // -> AUTHENTICATION MODULE
  703. await knex('authentication').insert({
  704. id: authModuleId,
  705. module: 'local',
  706. isEnabled: true,
  707. displayName: 'Local Authentication'
  708. })
  709. // -> USERS
  710. await knex('users').insert([
  711. {
  712. id: userAdminId,
  713. email: process.env.ADMIN_EMAIL ?? 'admin@example.com',
  714. auth: {
  715. [authModuleId]: {
  716. password: await bcrypt.hash(process.env.ADMIN_PASS || '12345678', 12),
  717. mustChangePwd: false, // TODO: Revert to true (below) once change password flow is implemented
  718. // mustChangePwd: !process.env.ADMIN_PASS,
  719. restrictLogin: false,
  720. tfaRequired: false,
  721. tfaSecret: ''
  722. }
  723. },
  724. name: 'Administrator',
  725. isSystem: false,
  726. isActive: true,
  727. isVerified: true,
  728. meta: {
  729. location: '',
  730. jobTitle: '',
  731. pronouns: ''
  732. },
  733. prefs: {
  734. timezone: 'America/New_York',
  735. dateFormat: 'YYYY-MM-DD',
  736. timeFormat: '12h',
  737. appearance: 'site',
  738. cvd: 'none'
  739. }
  740. },
  741. {
  742. id: userGuestId,
  743. email: 'guest@example.com',
  744. auth: {},
  745. name: 'Guest',
  746. isSystem: true,
  747. isActive: true,
  748. isVerified: true,
  749. meta: {},
  750. prefs: {
  751. timezone: 'America/New_York',
  752. dateFormat: 'YYYY-MM-DD',
  753. timeFormat: '12h',
  754. appearance: 'site',
  755. cvd: 'none'
  756. }
  757. }
  758. ])
  759. await knex('userGroups').insert([
  760. {
  761. userId: userAdminId,
  762. groupId: groupAdminId
  763. },
  764. {
  765. userId: userAdminId,
  766. groupId: groupUserId
  767. },
  768. {
  769. userId: userGuestId,
  770. groupId: groupGuestId
  771. }
  772. ])
  773. // -> BLOCKS
  774. await knex('blocks').insert({
  775. block: 'index',
  776. name: 'Index',
  777. description: 'Show a list of pages matching a path or set of tags.',
  778. icon: 'rules',
  779. isCustom: false,
  780. isEnabled: true,
  781. config: {},
  782. siteId: siteId
  783. })
  784. // -> NAVIGATION
  785. await knex('navigation').insert({
  786. id: siteId,
  787. items: JSON.stringify([
  788. {
  789. id: uuid(),
  790. type: 'header',
  791. label: 'Sample Header',
  792. visibilityGroups: []
  793. },
  794. {
  795. id: uuid(),
  796. type: 'link',
  797. icon: 'mdi-file-document-outline',
  798. label: 'Sample Link 1',
  799. target: '/',
  800. openInNewWindow: false,
  801. visibilityGroups: [],
  802. children: []
  803. },
  804. {
  805. id: uuid(),
  806. type: 'link',
  807. icon: 'mdi-book-open-variant',
  808. label: 'Sample Link 2',
  809. target: '/',
  810. openInNewWindow: false,
  811. visibilityGroups: [],
  812. children: []
  813. },
  814. {
  815. id: uuid(),
  816. type: 'separator',
  817. visibilityGroups: []
  818. },
  819. {
  820. id: uuid(),
  821. type: 'link',
  822. icon: 'mdi-airballoon',
  823. label: 'Sample Link 3',
  824. target: '/',
  825. openInNewWindow: false,
  826. visibilityGroups: [],
  827. children: []
  828. }
  829. ]),
  830. siteId: siteId
  831. })
  832. // -> STORAGE MODULE
  833. await knex('storage').insert({
  834. module: 'db',
  835. siteId,
  836. isEnabled: true,
  837. contentTypes: {
  838. activeTypes: ['pages', 'images', 'documents', 'others', 'large'],
  839. largeThreshold: '5MB'
  840. },
  841. assetDelivery: {
  842. streaming: true,
  843. directAccess: false
  844. },
  845. versioning: {
  846. enabled: false
  847. },
  848. state: {
  849. current: 'ok'
  850. }
  851. })
  852. // -> SCHEDULED JOBS
  853. await knex('jobSchedule').insert([
  854. {
  855. task: 'checkVersion',
  856. cron: '0 0 * * *',
  857. type: 'system'
  858. },
  859. {
  860. task: 'cleanJobHistory',
  861. cron: '5 0 * * *',
  862. type: 'system'
  863. },
  864. // {
  865. // task: 'refreshAutocomplete',
  866. // cron: '0 */6 * * *',
  867. // type: 'system'
  868. // },
  869. {
  870. task: 'updateLocales',
  871. cron: '0 0 * * *',
  872. type: 'system'
  873. }
  874. ])
  875. await knex('jobLock').insert({
  876. key: 'cron',
  877. lastCheckedBy: 'init',
  878. lastCheckedAt: DateTime.utc().minus({ hours: 1 }).toISO()
  879. })
  880. WIKI.logger.info('Completed 3.0.0 database migration.')
  881. }
  882. export function down (knex) { }