3.0.0.mjs 30 KB

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