sandstorm.js 17 KB

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