sandstorm.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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 isCommentOnly = false;
  183. const isNoComments = false;
  184. const permissionDoc = { userId, isActive, isAdmin, isNoComments, isCommentOnly };
  185. const boardMembers = Boards.findOne(sandstormBoard._id).members;
  186. const memberIndex = _.pluck(boardMembers, 'userId').indexOf(userId);
  187. let modifier;
  188. if (memberIndex > -1)
  189. modifier = { $set: { [`members.${memberIndex}`]: permissionDoc }};
  190. else if (!isActive)
  191. modifier = {};
  192. else
  193. modifier = { $push: { members: permissionDoc }};
  194. Boards.update(sandstormBoard._id, modifier);
  195. }
  196. Picker.route('/', (params, req, res) => {
  197. // Redirect the user to the hard-coded board. On the first launch the user
  198. // will be redirected to the board before its creation. But that's not a
  199. // problem thanks to the reactive board publication. We used to do this
  200. // redirection on the client side but that was sometimes visible on loading,
  201. // and the home page was accessible by pressing the back button of the
  202. // browser, a server-side redirection solves both of these issues.
  203. //
  204. // XXX Maybe the sandstorm http-bridge could provide some kind of "home URL"
  205. // in the manifest?
  206. const base = req.headers['x-sandstorm-base-path'];
  207. const { _id, slug } = sandstormBoard;
  208. const boardPath = FlowRouter.path('board', { id: _id, slug });
  209. res.writeHead(301, {
  210. Location: base + boardPath,
  211. });
  212. res.end();
  213. });
  214. // On the first launch of the instance a user is automatically created thanks
  215. // to the `accounts-sandstorm` package. After its creation we insert the
  216. // unique board document. Note that when the `Users.after.insert` hook is
  217. // called, the user is inserted into the database but not connected. So
  218. // despite the appearances `userId` is null in this block.
  219. Users.after.insert((userId, doc) => {
  220. if (!Boards.findOne(sandstormBoard._id)) {
  221. Boards.insert(sandstormBoard, { validate: false });
  222. Swimlanes.insert({
  223. title: 'Default',
  224. boardId: sandstormBoard._id,
  225. });
  226. Activities.update(
  227. { activityTypeId: sandstormBoard._id },
  228. { $set: { userId: doc._id }}
  229. );
  230. }
  231. // We rely on username uniqueness for the user mention feature, but
  232. // Sandstorm doesn't enforce this property -- see #352. Our strategy to
  233. // generate unique usernames from the Sandstorm `preferredHandle` is to
  234. // append a number that we increment until we generate a username that no
  235. // one already uses (eg, 'max', 'max1', 'max2').
  236. function generateUniqueUsername(username, appendNumber) {
  237. return username + String(appendNumber === 0 ? '' : appendNumber);
  238. }
  239. const username = doc.services.sandstorm.preferredHandle;
  240. let appendNumber = 0;
  241. while (Users.findOne({
  242. _id: { $ne: doc._id },
  243. username: generateUniqueUsername(username, appendNumber),
  244. })) {
  245. appendNumber += 1;
  246. }
  247. Users.update(doc._id, {
  248. $set: {
  249. username: generateUniqueUsername(username, appendNumber),
  250. 'profile.fullname': doc.services.sandstorm.name,
  251. 'profile.avatarUrl': doc.services.sandstorm.picture,
  252. },
  253. });
  254. updateUserPermissions(doc._id, doc.services.sandstorm.permissions);
  255. });
  256. Meteor.startup(() => {
  257. Users.find().observeChanges({
  258. changed(userId, fields) {
  259. const sandstormData = (fields.services || {}).sandstorm || {};
  260. if (sandstormData.name) {
  261. Users.update(userId, {
  262. $set: { 'profile.fullname': sandstormData.name },
  263. });
  264. }
  265. if (sandstormData.picture) {
  266. Users.update(userId, {
  267. $set: { 'profile.avatarUrl': sandstormData.picture },
  268. });
  269. }
  270. if (sandstormData.permissions) {
  271. updateUserPermissions(userId, sandstormData.permissions);
  272. }
  273. },
  274. });
  275. });
  276. // Wekan v0.8 didn’t implement the Sandstorm sharing model and instead kept
  277. // the visibility setting (“public” or “private”) in the UI as does the main
  278. // Meteor application. We need to enforce “public” visibility as the sharing
  279. // is now handled by Sandstorm.
  280. // See https://github.com/wekan/wekan/issues/346
  281. Migrations.add('enforce-public-visibility-for-sandstorm', () => {
  282. Boards.update('sandstorm', { $set: { permission: 'public' }});
  283. });
  284. // Monkey patch to work around the problem described in
  285. // https://github.com/sandstorm-io/meteor-accounts-sandstorm/pull/31
  286. const _httpMethods = HTTP.methods;
  287. HTTP.methods = (newMethods) => {
  288. Object.keys(newMethods).forEach((key) => {
  289. if (newMethods[key].auth) {
  290. newMethods[key].auth = function() {
  291. const sandstormID = this.req.headers['x-sandstorm-user-id'];
  292. const user = Meteor.users.findOne({'services.sandstorm.id': sandstormID});
  293. return user && user._id;
  294. };
  295. }
  296. });
  297. _httpMethods(newMethods);
  298. };
  299. }
  300. if (isSandstorm && Meteor.isClient) {
  301. let rpcCounter = 0;
  302. const rpcs = {};
  303. window.addEventListener('message', (event) => {
  304. if (event.source === window) {
  305. // Meteor likes to postmessage itself.
  306. return;
  307. }
  308. if ((event.source !== window.parent) ||
  309. typeof event.data !== 'object' ||
  310. typeof event.data.rpcId !== 'number') {
  311. throw new Error(`got unexpected postMessage: ${event}`);
  312. }
  313. const handler = rpcs[event.data.rpcId];
  314. if (!handler) {
  315. throw new Error(`no such rpc ID for event ${event}`);
  316. }
  317. delete rpcs[event.data.rpcId];
  318. handler(event.data);
  319. });
  320. function sendRpc(name, message) {
  321. const id = rpcCounter++;
  322. message.rpcId = id;
  323. const obj = {};
  324. obj[name] = message;
  325. window.parent.postMessage(obj, '*');
  326. return new Promise((resolve, reject) => {
  327. rpcs[id] = (response) => {
  328. if (response.error) {
  329. reject(new Error(response.error));
  330. } else {
  331. resolve(response);
  332. }
  333. };
  334. });
  335. }
  336. const powerboxDescriptors = {
  337. identity: 'EAhQAQEAABEBF1EEAQH_GN1RqXqYhMAAQAERAREBAQ',
  338. // Generated using the following code:
  339. //
  340. // Capnp.serializePacked(
  341. // Powerbox.PowerboxDescriptor,
  342. // { tags: [ {
  343. // id: "13872380404802116888",
  344. // value: Capnp.serialize(Identity.PowerboxTag, { permissions: [true, false] })
  345. // }]}).toString('base64')
  346. // .replace(/\//g, "_")
  347. // .replace(/\+/g, "-");
  348. };
  349. function doRequest(serializedPowerboxDescriptor, onSuccess) {
  350. return sendRpc('powerboxRequest', {
  351. query: [serializedPowerboxDescriptor],
  352. }).then((response) => {
  353. if (!response.canceled) {
  354. onSuccess(response);
  355. }
  356. });
  357. }
  358. window.sandstormRequestIdentity = function () {
  359. doRequest(powerboxDescriptors.identity, (response) => {
  360. Meteor.call('sandstormClaimIdentityRequest', response.token, response.descriptor);
  361. });
  362. };
  363. // Since the Sandstorm grain is displayed in an iframe of the Sandstorm shell,
  364. // we need to explicitly expose meta data like the page title or the URL path
  365. // so that they could appear in the browser window.
  366. // See https://docs.sandstorm.io/en/latest/developing/path/
  367. function updateSandstormMetaData(msg) {
  368. return window.parent.postMessage(msg, '*');
  369. }
  370. FlowRouter.triggers.enter([({ path }) => {
  371. updateSandstormMetaData({ setPath: path });
  372. }]);
  373. Tracker.autorun(() => {
  374. updateSandstormMetaData({ setTitle: DocHead.getTitle() });
  375. });
  376. // Runtime redirection from the home page to the unique board -- since the
  377. // home page contains a list of a single board it's not worth to display.
  378. //
  379. // XXX Hack. The home route is already defined at this point so we need to
  380. // add the redirection trigger to the internal route object.
  381. FlowRouter._routesMap.home._triggersEnter.push((context, redirect) => {
  382. redirect(FlowRouter.path('board', {
  383. id: sandstormBoard._id,
  384. slug: sandstormBoard.slug,
  385. }));
  386. });
  387. // XXX Hack. `Meteor.absoluteUrl` doesn't work in Sandstorm, since every
  388. // session has a different URL whereas Meteor computes absoluteUrl based on
  389. // the ROOT_URL environment variable. So we overwrite this function on a
  390. // sandstorm client to return relative paths instead of absolutes.
  391. const _absoluteUrl = Meteor.absoluteUrl;
  392. const _defaultOptions = Meteor.absoluteUrl.defaultOptions;
  393. Meteor.absoluteUrl = (path, options) => {
  394. const url = _absoluteUrl(path, options);
  395. return url.replace(/^https?:\/\/127\.0\.0\.1:[0-9]{2,5}/, '');
  396. };
  397. Meteor.absoluteUrl.defaultOptions = _defaultOptions;
  398. // XXX Hack to fix https://github.com/wefork/wekan/issues/27
  399. // Sandstorm Wekan instances only ever have a single board, so there is no need
  400. // to cache per-board subscriptions.
  401. SubsManager.prototype.subscribe = function(...params) {
  402. return Meteor.subscribe(...params);
  403. };
  404. }
  405. // We use this blaze helper in the UI to hide some templates that does not make
  406. // sense in the context of sandstorm, like board staring, board archiving, user
  407. // name edition, etc.
  408. Blaze.registerHelper('isSandstorm', isSandstorm);