sandstorm.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  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. // a) OLD 2021-11-29: First user is admin
  210. //const isAdmin = permissions.indexOf('configure') > -1;
  211. // b) NEW 2021-11-29: Every user is admin:
  212. // https://github.com/wekan/wekan/issues/3423
  213. const isAdmin = true;
  214. const isCommentOnly = false;
  215. const isNoComments = false;
  216. const isWorker = false;
  217. const permissionDoc = {
  218. userId,
  219. isActive,
  220. isAdmin,
  221. isNoComments,
  222. isCommentOnly,
  223. isWorker,
  224. };
  225. const boardMembers = Boards.findOne(sandstormBoard._id).members;
  226. const memberIndex = _.pluck(boardMembers, 'userId').indexOf(userId);
  227. let modifier;
  228. if (memberIndex > -1)
  229. modifier = { $set: { [`members.${memberIndex}`]: permissionDoc } };
  230. else if (!isActive) modifier = {};
  231. else modifier = { $push: { members: permissionDoc } };
  232. Boards.update(sandstormBoard._id, modifier);
  233. }
  234. Picker.route('/', (params, req, res) => {
  235. // Redirect the user to the hard-coded board. On the first launch the user
  236. // will be redirected to the board before its creation. But that's not a
  237. // problem thanks to the reactive board publication. We used to do this
  238. // redirection on the client side but that was sometimes visible on loading,
  239. // and the home page was accessible by pressing the back button of the
  240. // browser, a server-side redirection solves both of these issues.
  241. //
  242. // XXX Maybe the sandstorm http-bridge could provide some kind of "home URL"
  243. // in the manifest?
  244. const base = req.headers['x-sandstorm-base-path'];
  245. const { _id, slug } = sandstormBoard;
  246. const boardPath = FlowRouter.path('board', { id: _id, slug });
  247. res.writeHead(301, {
  248. Location: base + boardPath,
  249. });
  250. res.end();
  251. });
  252. // On the first launch of the instance a user is automatically created thanks
  253. // to the `accounts-sandstorm` package. After its creation we insert the
  254. // unique board document. Note that when the `Users.after.insert` hook is
  255. // called, the user is inserted into the database but not connected. So
  256. // despite the appearances `userId` is null in this block.
  257. Users.after.insert((userId, doc) => {
  258. if (!Boards.findOne(sandstormBoard._id)) {
  259. Boards.insert(sandstormBoard, { validate: false });
  260. Swimlanes.insert({
  261. title: 'Default',
  262. boardId: sandstormBoard._id,
  263. });
  264. Activities.update(
  265. { activityTypeId: sandstormBoard._id },
  266. { $set: { userId: doc._id } },
  267. );
  268. }
  269. // We rely on username uniqueness for the user mention feature, but
  270. // Sandstorm doesn't enforce this property -- see #352. Our strategy to
  271. // generate unique usernames from the Sandstorm `preferredHandle` is to
  272. // append a number that we increment until we generate a username that no
  273. // one already uses (eg, 'max', 'max1', 'max2').
  274. function generateUniqueUsername(username, appendNumber) {
  275. return username + String(appendNumber === 0 ? '' : appendNumber);
  276. }
  277. const username = doc.services.sandstorm.preferredHandle;
  278. let appendNumber = 0;
  279. while (
  280. Users.findOne({
  281. _id: { $ne: doc._id },
  282. username: generateUniqueUsername(username, appendNumber),
  283. })
  284. ) {
  285. appendNumber += 1;
  286. }
  287. Users.update(doc._id, {
  288. $set: {
  289. username: generateUniqueUsername(username, appendNumber),
  290. 'profile.fullname': doc.services.sandstorm.name,
  291. 'profile.avatarUrl': doc.services.sandstorm.picture,
  292. },
  293. });
  294. updateUserPermissions(doc._id, doc.services.sandstorm.permissions);
  295. });
  296. Meteor.startup(() => {
  297. Users.find().observeChanges({
  298. changed(userId, fields) {
  299. const sandstormData = (fields.services || {}).sandstorm || {};
  300. if (sandstormData.name) {
  301. Users.update(userId, {
  302. $set: { 'profile.fullname': sandstormData.name },
  303. });
  304. }
  305. if (sandstormData.picture) {
  306. Users.update(userId, {
  307. $set: { 'profile.avatarUrl': sandstormData.picture },
  308. });
  309. }
  310. if (sandstormData.permissions) {
  311. updateUserPermissions(userId, sandstormData.permissions);
  312. }
  313. },
  314. });
  315. });
  316. // Wekan v0.8 didn’t implement the Sandstorm sharing model and instead kept
  317. // the visibility setting (“public” or “private”) in the UI as does the main
  318. // Meteor application. We need to enforce “public” visibility as the sharing
  319. // is now handled by Sandstorm.
  320. // See https://github.com/wekan/wekan/issues/346
  321. Migrations.add('enforce-public-visibility-for-sandstorm', () => {
  322. Boards.update('sandstorm', { $set: { permission: 'public' } });
  323. });
  324. // Monkey patch to work around the problem described in
  325. // https://github.com/sandstorm-io/meteor-accounts-sandstorm/pull/31
  326. const _httpMethods = HTTP.methods;
  327. HTTP.methods = newMethods => {
  328. Object.keys(newMethods).forEach(key => {
  329. if (newMethods[key].auth) {
  330. newMethods[key].auth = function() {
  331. const sandstormID = this.req.headers['x-sandstorm-user-id'];
  332. const user = Meteor.users.findOne({
  333. 'services.sandstorm.id': sandstormID,
  334. });
  335. return user && user._id;
  336. };
  337. }
  338. });
  339. _httpMethods(newMethods);
  340. };
  341. }
  342. if (isSandstorm && Meteor.isClient) {
  343. let rpcCounter = 0;
  344. const rpcs = {};
  345. window.addEventListener('message', event => {
  346. if (event.source === window) {
  347. // Meteor likes to postmessage itself.
  348. return;
  349. }
  350. if (
  351. event.source !== window.parent ||
  352. typeof event.data !== 'object' ||
  353. typeof event.data.rpcId !== 'number'
  354. ) {
  355. throw new Error(`got unexpected postMessage: ${event}`);
  356. }
  357. const handler = rpcs[event.data.rpcId];
  358. if (!handler) {
  359. throw new Error(`no such rpc ID for event ${event}`);
  360. }
  361. delete rpcs[event.data.rpcId];
  362. handler(event.data);
  363. });
  364. function sendRpc(name, message) {
  365. const id = rpcCounter++;
  366. message.rpcId = id;
  367. const obj = {};
  368. obj[name] = message;
  369. window.parent.postMessage(obj, '*');
  370. return new Promise((resolve, reject) => {
  371. rpcs[id] = response => {
  372. if (response.error) {
  373. reject(new Error(response.error));
  374. } else {
  375. resolve(response);
  376. }
  377. };
  378. });
  379. }
  380. const powerboxDescriptors = {
  381. identity: 'EAhQAQEAABEBF1EEAQH_GN1RqXqYhMAAQAERAREBAQ',
  382. // Generated using the following code:
  383. //
  384. // Capnp.serializePacked(
  385. // Powerbox.PowerboxDescriptor,
  386. // { tags: [ {
  387. // id: "13872380404802116888",
  388. // value: Capnp.serialize(Identity.PowerboxTag, { permissions: [true, false] })
  389. // }]}).toString('base64')
  390. // .replace(/\//g, "_")
  391. // .replace(/\+/g, "-");
  392. };
  393. function doRequest(serializedPowerboxDescriptor, onSuccess) {
  394. return sendRpc('powerboxRequest', {
  395. query: [serializedPowerboxDescriptor],
  396. }).then(response => {
  397. if (!response.canceled) {
  398. onSuccess(response);
  399. }
  400. });
  401. }
  402. window.sandstormRequestIdentity = function() {
  403. doRequest(powerboxDescriptors.identity, response => {
  404. Meteor.call(
  405. 'sandstormClaimIdentityRequest',
  406. response.token,
  407. response.descriptor,
  408. );
  409. });
  410. };
  411. // Since the Sandstorm grain is displayed in an iframe of the Sandstorm shell,
  412. // we need to explicitly expose meta data like the page title or the URL path
  413. // so that they could appear in the browser window.
  414. // See https://docs.sandstorm.io/en/latest/developing/path/
  415. function updateSandstormMetaData(msg) {
  416. return window.parent.postMessage(msg, '*');
  417. }
  418. FlowRouter.triggers.enter([
  419. ({ path }) => {
  420. updateSandstormMetaData({ setPath: path });
  421. },
  422. ]);
  423. Tracker.autorun(() => {
  424. updateSandstormMetaData({ setTitle: DocHead.getTitle() });
  425. });
  426. // Runtime redirection from the home page to the unique board -- since the
  427. // home page contains a list of a single board it's not worth to display.
  428. //
  429. // XXX Hack. The home route is already defined at this point so we need to
  430. // add the redirection trigger to the internal route object.
  431. //FlowRouter._routesMap.home._triggersEnter.push((context, redirect) => {
  432. // redirect(FlowRouter.path('board', {
  433. // id: sandstormBoard._id,
  434. // slug: sandstormBoard.slug,
  435. // }));
  436. //});
  437. // XXX Hack. `Meteor.absoluteUrl` doesn't work in Sandstorm, since every
  438. // session has a different URL whereas Meteor computes absoluteUrl based on
  439. // the ROOT_URL environment variable. So we overwrite this function on a
  440. // sandstorm client to return relative paths instead of absolutes.
  441. const _absoluteUrl = Meteor.absoluteUrl;
  442. const _defaultOptions = Meteor.absoluteUrl.defaultOptions;
  443. Meteor.absoluteUrl = (path, options) => {
  444. const url = _absoluteUrl(path, options);
  445. return url.replace(/^https?:\/\/127\.0\.0\.1:[0-9]{2,5}/, '');
  446. };
  447. Meteor.absoluteUrl.defaultOptions = _defaultOptions;
  448. // XXX Hack to fix https://github.com/wefork/wekan/issues/27
  449. // Sandstorm Wekan instances only ever have a single board, so there is no need
  450. // to cache per-board subscriptions.
  451. //SubsManager.prototype.subscribe = function(...params) {
  452. // return Meteor.subscribe(...params);
  453. //};
  454. }
  455. // We use this blaze helper in the UI to hide some templates that does not make
  456. // sense in the context of sandstorm, like board staring, board archiving, user
  457. // name edition, etc.
  458. Blaze.registerHelper('isSandstorm', isSandstorm);