sandstorm.js 16 KB

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