sandstorm.js 17 KB

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