sandstorm.js 16 KB

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