sandstorm.js 16 KB

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