sandstorm.js 16 KB

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