sandstorm.js 17 KB

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