sandstorm.js 17 KB

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