sandstorm.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. import { ReactiveCache } from '/imports/reactiveCache';
  2. import { Meteor } from 'meteor/meteor';
  3. import { Picker } from 'meteor/communitypackages:picker';
  4. // Sandstorm context is detected using the METEOR_SETTINGS environment variable
  5. // in the package definition.
  6. const isSandstorm = Meteor.settings?.public?.sandstorm;
  7. // In sandstorm we only have one board per sandstorm instance. Since we want to
  8. // keep most of our code unchanged, we simply hard-code a board `_id` and
  9. // redirect the user to this particular board.
  10. const sandstormBoard = {
  11. _id: 'sandstorm',
  12. // XXX Should be shared with the grain instance name.
  13. title: 'Wekan',
  14. slug: 'libreboard',
  15. members: [],
  16. // Board access security is handled by sandstorm, so in our point of view we
  17. // can alway assume that the board is public (unauthorized users won't be able
  18. // to access it anyway).
  19. permission: 'public',
  20. };
  21. if (isSandstorm && Meteor.isServer) {
  22. const fs = require('fs');
  23. const Capnp = Npm.require('capnp');
  24. const Package = Capnp.importSystem('sandstorm/package.capnp');
  25. const Powerbox = Capnp.importSystem('sandstorm/powerbox.capnp');
  26. const Identity = Capnp.importSystem('sandstorm/identity.capnp');
  27. const SandstormHttpBridge = Capnp.importSystem(
  28. 'sandstorm/sandstorm-http-bridge.capnp',
  29. ).SandstormHttpBridge;
  30. let httpBridge = null;
  31. let capnpConnection = null;
  32. const bridgeConfig = Capnp.parse(
  33. Package.BridgeConfig,
  34. fs.readFileSync('/sandstorm-http-bridge-config'),
  35. );
  36. function getHttpBridge() {
  37. if (!httpBridge) {
  38. capnpConnection = Capnp.connect('unix:/tmp/sandstorm-api');
  39. httpBridge = capnpConnection.restore(null, SandstormHttpBridge);
  40. }
  41. return httpBridge;
  42. }
  43. Meteor.methods({
  44. sandstormClaimIdentityRequest(token, descriptor) {
  45. check(token, String);
  46. check(descriptor, String);
  47. const parsedDescriptor = Capnp.parse(
  48. Powerbox.PowerboxDescriptor,
  49. Buffer.from(descriptor, 'base64'),
  50. { packed: true },
  51. );
  52. const tag = Capnp.parse(
  53. Identity.Identity.PowerboxTag,
  54. parsedDescriptor.tags[0].value,
  55. );
  56. const permissions = [];
  57. if (tag.permissions[1]) {
  58. permissions.push('configure');
  59. }
  60. if (tag.permissions[0]) {
  61. permissions.push('participate');
  62. }
  63. const sessionId = this.connection.sandstormSessionId();
  64. const httpBridge = getHttpBridge();
  65. const session = httpBridge.getSessionContext(sessionId).context;
  66. const api = httpBridge.getSandstormApi(sessionId).api;
  67. Meteor.wrapAsync(done => {
  68. session
  69. .claimRequest(token)
  70. .then(response => {
  71. const identity = response.cap.castAs(Identity.Identity);
  72. const promises = [
  73. api.getIdentityId(identity),
  74. identity.getProfile(),
  75. httpBridge.saveIdentity(identity),
  76. ];
  77. return Promise.all(promises).then(responses => {
  78. const identityId = responses[0].id.toString('hex').slice(0, 32);
  79. const profile = responses[1].profile;
  80. return profile.picture.getUrl().then(response => {
  81. const sandstormInfo = {
  82. id: identityId,
  83. name: profile.displayName.defaultText,
  84. permissions,
  85. picture: `${response.protocol}://${response.hostPath}`,
  86. preferredHandle: profile.preferredHandle,
  87. pronouns: profile.pronouns,
  88. };
  89. const login = Accounts.updateOrCreateUserFromExternalService(
  90. 'sandstorm',
  91. sandstormInfo,
  92. { profile: { name: sandstormInfo.name } },
  93. );
  94. updateUserPermissions(login.userId, permissions);
  95. done();
  96. });
  97. });
  98. })
  99. .catch(e => {
  100. done(e, null);
  101. });
  102. })();
  103. },
  104. });
  105. function reportActivity(sessionId, path, type, users, caption) {
  106. const httpBridge = getHttpBridge();
  107. const session = httpBridge.getSessionContext(sessionId).context;
  108. Meteor.wrapAsync(done => {
  109. return Promise.all(
  110. users.map(user => {
  111. return httpBridge
  112. .getSavedIdentity(user.id)
  113. .then(response => {
  114. // Call getProfile() to make sure that the identity successfully resolves.
  115. // (In C++ we would instead call whenResolved() here.)
  116. const identity = response.identity;
  117. return identity.getProfile().then(() => {
  118. return {
  119. identity,
  120. mentioned: !!user.mentioned,
  121. subscribed: !!user.subscribed,
  122. };
  123. });
  124. })
  125. .catch(() => {
  126. // Ignore identities that fail to restore. Either they were added before we set
  127. // `saveIdentityCaps` to true, or they have lost access to the board.
  128. });
  129. }),
  130. )
  131. .then(maybeUsers => {
  132. const users = maybeUsers.filter(u => !!u);
  133. const event = { path, type, users };
  134. if (caption) {
  135. event.notification = { caption };
  136. }
  137. return session.activity(event);
  138. })
  139. .then(
  140. () => done(),
  141. e => done(e),
  142. );
  143. })();
  144. }
  145. Meteor.startup(() => {
  146. Activities.after.insert((userId, doc) => {
  147. // HACK: We need the connection that's making the request in order to read the
  148. // Sandstorm session ID.
  149. const invocation = DDP._CurrentInvocation.get(); // eslint-disable-line no-undef
  150. if (invocation) {
  151. const sessionId = invocation.connection.sandstormSessionId();
  152. const eventTypes = bridgeConfig.viewInfo.eventTypes;
  153. const defIdx = eventTypes.findIndex(
  154. def => def.name === doc.activityType,
  155. );
  156. if (defIdx >= 0) {
  157. const users = {};
  158. function ensureUserListed(userId) {
  159. if (!users[userId]) {
  160. const user = Meteor.users.findOne(userId);
  161. if (user) {
  162. users[userId] = { id: user.services.sandstorm.id };
  163. } else {
  164. return false;
  165. }
  166. }
  167. return true;
  168. }
  169. function mentionedUser(userId) {
  170. if (ensureUserListed(userId)) {
  171. users[userId].mentioned = true;
  172. }
  173. }
  174. function subscribedUser(userId) {
  175. if (ensureUserListed(userId)) {
  176. users[userId].subscribed = true;
  177. }
  178. }
  179. let path = '';
  180. let caption = null;
  181. if (doc.cardId) {
  182. path = `b/sandstorm/libreboard/${doc.cardId}`;
  183. ReactiveCache.getCard(doc.cardId).members.map(subscribedUser);
  184. }
  185. if (doc.memberId) {
  186. mentionedUser(doc.memberId);
  187. }
  188. if (doc.activityType === 'addComment') {
  189. const comment = ReactiveCache.getCardComment(doc.commentId);
  190. caption = { defaultText: comment.text };
  191. const activeMembers = _.pluck(
  192. ReactiveCache.getBoard(sandstormBoard._id).activeMembers(),
  193. 'userId',
  194. );
  195. (comment.text.match(/\B@([\w.]*)/g) || []).forEach(username => {
  196. const user = Meteor.users.findOne({
  197. username: username.slice(1),
  198. });
  199. if (user && activeMembers.indexOf(user._id) !== -1) {
  200. mentionedUser(user._id);
  201. }
  202. });
  203. }
  204. reportActivity(sessionId, path, defIdx, _.values(users), caption);
  205. }
  206. }
  207. });
  208. });
  209. function updateUserPermissions(userId, permissions) {
  210. const isActive = permissions.indexOf('participate') > -1;
  211. const isAdmin = permissions.indexOf('configure') > -1;
  212. const isCommentOnly = false;
  213. const isNoComments = false;
  214. const isWorker = false;
  215. const permissionDoc = {
  216. userId,
  217. isActive,
  218. isAdmin,
  219. isNoComments,
  220. isCommentOnly,
  221. isWorker,
  222. };
  223. const boardMembers = ReactiveCache.getBoard(sandstormBoard._id).members;
  224. const memberIndex = _.pluck(boardMembers, 'userId').indexOf(userId);
  225. let modifier;
  226. if (memberIndex > -1)
  227. modifier = { $set: { [`members.${memberIndex}`]: permissionDoc } };
  228. else if (!isActive) modifier = {};
  229. else modifier = { $push: { members: permissionDoc } };
  230. Boards.update(sandstormBoard._id, modifier);
  231. }
  232. Picker.route('/', (params, req, res) => {
  233. // Redirect the user to the hard-coded board. On the first launch the user
  234. // will be redirected to the board before its creation. But that's not a
  235. // problem thanks to the reactive board publication. We used to do this
  236. // redirection on the client side but that was sometimes visible on loading,
  237. // and the home page was accessible by pressing the back button of the
  238. // browser, a server-side redirection solves both of these issues.
  239. //
  240. // XXX Maybe the sandstorm http-bridge could provide some kind of "home URL"
  241. // in the manifest?
  242. const base = req.headers['x-sandstorm-base-path'];
  243. const { _id, slug } = sandstormBoard;
  244. const boardPath = FlowRouter.path('board', { id: _id, slug });
  245. res.writeHead(301, {
  246. Location: base + boardPath,
  247. });
  248. res.end();
  249. });
  250. // On the first launch of the instance a user is automatically created thanks
  251. // to the `accounts-sandstorm` package. After its creation we insert the
  252. // unique board document. Note that when the `Users.after.insert` hook is
  253. // called, the user is inserted into the database but not connected. So
  254. // despite the appearances `userId` is null in this block.
  255. Users.after.insert((userId, doc) => {
  256. if (!ReactiveCache.getBoard(sandstormBoard._id)) {
  257. Boards.insert(sandstormBoard, { validate: false });
  258. Swimlanes.insert({
  259. title: 'Default',
  260. boardId: sandstormBoard._id,
  261. });
  262. Activities.update(
  263. { activityTypeId: sandstormBoard._id },
  264. { $set: { userId: doc._id } },
  265. );
  266. }
  267. // We rely on username uniqueness for the user mention feature, but
  268. // Sandstorm doesn't enforce this property -- see #352. Our strategy to
  269. // generate unique usernames from the Sandstorm `preferredHandle` is to
  270. // append a number that we increment until we generate a username that no
  271. // one already uses (eg, 'max', 'max1', 'max2').
  272. function generateUniqueUsername(username, appendNumber) {
  273. return username + String(appendNumber === 0 ? '' : appendNumber);
  274. }
  275. const username = doc.services.sandstorm.preferredHandle;
  276. let appendNumber = 0;
  277. while (
  278. ReactiveCache.getUser({
  279. _id: { $ne: doc._id },
  280. username: generateUniqueUsername(username, appendNumber),
  281. })
  282. ) {
  283. appendNumber += 1;
  284. }
  285. Users.update(doc._id, {
  286. $set: {
  287. username: generateUniqueUsername(username, appendNumber),
  288. 'profile.fullname': doc.services.sandstorm.name,
  289. 'profile.avatarUrl': doc.services.sandstorm.picture,
  290. },
  291. });
  292. updateUserPermissions(doc._id, doc.services.sandstorm.permissions);
  293. });
  294. Meteor.startup(() => {
  295. Users.find().observeChanges({
  296. changed(userId, fields) {
  297. const sandstormData = (fields.services || {}).sandstorm || {};
  298. if (sandstormData.name) {
  299. Users.update(userId, {
  300. $set: { 'profile.fullname': sandstormData.name },
  301. });
  302. }
  303. if (sandstormData.picture) {
  304. Users.update(userId, {
  305. $set: { 'profile.avatarUrl': sandstormData.picture },
  306. });
  307. }
  308. if (sandstormData.permissions) {
  309. updateUserPermissions(userId, sandstormData.permissions);
  310. }
  311. },
  312. });
  313. });
  314. // Wekan v0.8 didn’t implement the Sandstorm sharing model and instead kept
  315. // the visibility setting (“public” or “private”) in the UI as does the main
  316. // Meteor application. We need to enforce “public” visibility as the sharing
  317. // is now handled by Sandstorm.
  318. // See https://github.com/wekan/wekan/issues/346
  319. Migrations.add('enforce-public-visibility-for-sandstorm', () => {
  320. Boards.update('sandstorm', { $set: { permission: 'public' } });
  321. });
  322. // Monkey patch to work around the problem described in
  323. // https://github.com/sandstorm-io/meteor-accounts-sandstorm/pull/31
  324. const _httpMethods = HTTP.methods;
  325. HTTP.methods = newMethods => {
  326. Object.keys(newMethods).forEach(key => {
  327. if (newMethods[key].auth) {
  328. newMethods[key].auth = function() {
  329. const sandstormID = this.req.headers['x-sandstorm-user-id'];
  330. const user = Meteor.users.findOne({
  331. 'services.sandstorm.id': sandstormID,
  332. });
  333. return user && user._id;
  334. };
  335. }
  336. });
  337. _httpMethods(newMethods);
  338. };
  339. }
  340. if (isSandstorm && Meteor.isClient) {
  341. let rpcCounter = 0;
  342. const rpcs = {};
  343. window.addEventListener('message', event => {
  344. if (event.source === window) {
  345. // Meteor likes to postmessage itself.
  346. return;
  347. }
  348. if (
  349. event.source !== window.parent ||
  350. typeof event.data !== 'object' ||
  351. typeof event.data.rpcId !== 'number'
  352. ) {
  353. throw new Error(`got unexpected postMessage: ${event}`);
  354. }
  355. const handler = rpcs[event.data.rpcId];
  356. if (!handler) {
  357. throw new Error(`no such rpc ID for event ${event}`);
  358. }
  359. delete rpcs[event.data.rpcId];
  360. handler(event.data);
  361. });
  362. function sendRpc(name, message) {
  363. const id = rpcCounter++;
  364. message.rpcId = id;
  365. const obj = {};
  366. obj[name] = message;
  367. window.parent.postMessage(obj, '*');
  368. return new Promise((resolve, reject) => {
  369. rpcs[id] = response => {
  370. if (response.error) {
  371. reject(new Error(response.error));
  372. } else {
  373. resolve(response);
  374. }
  375. };
  376. });
  377. }
  378. const powerboxDescriptors = {
  379. identity: 'EAhQAQEAABEBF1EEAQH_GN1RqXqYhMAAQAERAREBAQ',
  380. // Generated using the following code:
  381. //
  382. // Capnp.serializePacked(
  383. // Powerbox.PowerboxDescriptor,
  384. // { tags: [ {
  385. // id: "13872380404802116888",
  386. // value: Capnp.serialize(Identity.PowerboxTag, { permissions: [true, false] })
  387. // }]}).toString('base64')
  388. // .replace(/\//g, "_")
  389. // .replace(/\+/g, "-");
  390. };
  391. function doRequest(serializedPowerboxDescriptor, onSuccess) {
  392. return sendRpc('powerboxRequest', {
  393. query: [serializedPowerboxDescriptor],
  394. }).then(response => {
  395. if (!response.canceled) {
  396. onSuccess(response);
  397. }
  398. });
  399. }
  400. window.sandstormRequestIdentity = function() {
  401. doRequest(powerboxDescriptors.identity, response => {
  402. Meteor.call(
  403. 'sandstormClaimIdentityRequest',
  404. response.token,
  405. response.descriptor,
  406. );
  407. });
  408. };
  409. // Since the Sandstorm grain is displayed in an iframe of the Sandstorm shell,
  410. // we need to explicitly expose meta data like the page title or the URL path
  411. // so that they could appear in the browser window.
  412. // See https://docs.sandstorm.io/en/latest/developing/path/
  413. function updateSandstormMetaData(msg) {
  414. return window.parent.postMessage(msg, '*');
  415. }
  416. FlowRouter.triggers.enter([
  417. ({ path }) => {
  418. updateSandstormMetaData({ setPath: path });
  419. },
  420. ]);
  421. Tracker.autorun(() => {
  422. updateSandstormMetaData({ setTitle: DocHead.getTitle() });
  423. });
  424. // Runtime redirection from the home page to the unique board -- since the
  425. // home page contains a list of a single board it's not worth to display.
  426. //
  427. // XXX Hack. The home route is already defined at this point so we need to
  428. // add the redirection trigger to the internal route object.
  429. //FlowRouter._routesMap.home._triggersEnter.push((context, redirect) => {
  430. // redirect(FlowRouter.path('board', {
  431. // id: sandstormBoard._id,
  432. // slug: sandstormBoard.slug,
  433. // }));
  434. //});
  435. // XXX Hack. `Meteor.absoluteUrl` doesn't work in Sandstorm, since every
  436. // session has a different URL whereas Meteor computes absoluteUrl based on
  437. // the ROOT_URL environment variable. So we overwrite this function on a
  438. // sandstorm client to return relative paths instead of absolutes.
  439. const _absoluteUrl = Meteor.absoluteUrl;
  440. const _defaultOptions = Meteor.absoluteUrl.defaultOptions;
  441. Meteor.absoluteUrl = (path, options) => {
  442. const url = _absoluteUrl(path, options);
  443. return url.replace(/^https?:\/\/127\.0\.0\.1:[0-9]{2,5}/, '');
  444. };
  445. Meteor.absoluteUrl.defaultOptions = _defaultOptions;
  446. // XXX Hack to fix https://github.com/wefork/wekan/issues/27
  447. // Sandstorm Wekan instances only ever have a single board, so there is no need
  448. // to cache per-board subscriptions.
  449. //SubsManager.prototype.subscribe = function(...params) {
  450. // return Meteor.subscribe(...params);
  451. //};
  452. }
  453. // We use this blaze helper in the UI to hide some templates that does not make
  454. // sense in the context of sandstorm, like board staring, board archiving, user
  455. // name edition, etc.
  456. Blaze.registerHelper('isSandstorm', isSandstorm);