server.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. // Copyright (c) 2014 Sandstorm Development Group, Inc. and contributors
  2. // Licensed under the MIT License:
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. if (process.env.SANDSTORM) {
  22. __meteor_runtime_config__.SANDSTORM = true;
  23. }
  24. if (__meteor_runtime_config__.SANDSTORM) {
  25. if (Package["accounts-base"]) {
  26. // Highlander Mode: Disable all non-Sandstorm login mechanisms.
  27. Package["accounts-base"].Accounts.validateLoginAttempt(function (attempt) {
  28. if (!attempt.allowed) {
  29. return false;
  30. }
  31. if (attempt.type !== "sandstorm") {
  32. throw new Meteor.Error(403, "Non-Sandstorm login mechanisms disabled on Sandstorm.");
  33. }
  34. return true;
  35. });
  36. Package["accounts-base"].Accounts.validateNewUser(function (user) {
  37. if (!user.services.sandstorm) {
  38. throw new Meteor.Error(403, "Non-Sandstorm login mechanisms disabled on Sandstorm.");
  39. }
  40. return true;
  41. });
  42. }
  43. var Future = Npm.require("fibers/future");
  44. var inMeteor = Meteor.bindEnvironment(function (callback) {
  45. callback();
  46. });
  47. var logins = {};
  48. // Maps tokens to currently-waiting login method calls.
  49. if (Package["accounts-base"]) {
  50. Meteor.users.createIndex("services.sandstorm.id", {unique: 1, sparse: 1});
  51. }
  52. Meteor.onConnection(function (connection) {
  53. connection._sandstormUser = null;
  54. connection._sandstormSessionId = null;
  55. connection._sandstormTabId = null;
  56. connection.sandstormUser = function () {
  57. if (!connection._sandstormUser) {
  58. throw new Meteor.Error(400, "Client did not complete authentication handshake.");
  59. }
  60. return this._sandstormUser;
  61. };
  62. connection.sandstormSessionId = function () {
  63. if (!connection._sandstormUser) {
  64. throw new Meteor.Error(400, "Client did not complete authentication handshake.");
  65. }
  66. return this._sandstormSessionId;
  67. }
  68. connection.sandstormTabId = function () {
  69. if (!connection._sandstormUser) {
  70. throw new Meteor.Error(400, "Client did not complete authentication handshake.");
  71. }
  72. return this._sandstormTabId;
  73. }
  74. });
  75. Meteor.methods({
  76. loginWithSandstorm: function (token) {
  77. check(token, String);
  78. var future = new Future();
  79. logins[token] = future;
  80. var timeout = setTimeout(function () {
  81. future.throw(new Meteor.Error("timeout", "Gave up waiting for login rendezvous XHR."));
  82. }, 10000);
  83. var info;
  84. try {
  85. info = future.wait();
  86. } finally {
  87. clearTimeout(timeout);
  88. delete logins[token];
  89. }
  90. // Set connection info. The call to setUserId() resets all publishes. We update the
  91. // connection's sandstorm info first so that when the publishes are re-run they'll see the
  92. // new info. In theory we really want to update it exactly when this.userId is updated, but
  93. // we'd have to dig into Meteor internals to pull that off. Probably updating it a little
  94. // early is fine?
  95. //
  96. // Note that calling setUserId() with the same ID a second time still goes through the motions
  97. // of restarting all subscriptions, which is important if the permissions changed. Hopefully
  98. // Meteor won't decide to "optimize" this by returning early if the user ID hasn't changed.
  99. this.connection._sandstormUser = info.sandstorm;
  100. this.connection._sandstormSessionId = info.sessionId;
  101. this.connection._sandstormTabId = info.tabId;
  102. this.setUserId(info.userId);
  103. return info;
  104. }
  105. });
  106. WebApp.rawConnectHandlers.use(function (req, res, next) {
  107. if (req.url === "/.sandstorm-login") {
  108. handlePostToken(req, res);
  109. return;
  110. }
  111. return next();
  112. });
  113. function readAll(stream) {
  114. var future = new Future();
  115. var chunks = [];
  116. stream.on("data", function (chunk) {
  117. chunks.push(chunk.toString());
  118. });
  119. stream.on("error", function (err) {
  120. future.throw(err);
  121. });
  122. stream.on("end", function () {
  123. future.return();
  124. });
  125. future.wait();
  126. return chunks.join("");
  127. }
  128. var handlePostToken = Meteor.bindEnvironment(function (req, res) {
  129. inMeteor(function () {
  130. try {
  131. // Note that cross-origin POSTs cannot set arbitrary Content-Types without explicit CORS
  132. // permission, so this effectively prevents XSRF.
  133. if (req.headers["content-type"].split(";")[0].trim() !== "application/x-sandstorm-login-token") {
  134. throw new Error("wrong Content-Type for .sandstorm-login: " + req.headers["content-type"]);
  135. }
  136. var token = readAll(req);
  137. var future = logins[token];
  138. if (!future) {
  139. throw new Error("no current login request matching token");
  140. }
  141. var permissions = req.headers["x-sandstorm-permissions"];
  142. if (permissions && permissions !== "") {
  143. permissions = permissions.split(",");
  144. } else {
  145. permissions = [];
  146. }
  147. var sandstormInfo = {
  148. id: req.headers["x-sandstorm-user-id"] || null,
  149. name: decodeURIComponent(req.headers["x-sandstorm-username"]),
  150. permissions: permissions,
  151. picture: req.headers["x-sandstorm-user-picture"] || null,
  152. preferredHandle: req.headers["x-sandstorm-preferred-handle"] || null,
  153. pronouns: req.headers["x-sandstorm-user-pronouns"] || null,
  154. };
  155. var userInfo = {sandstorm: sandstormInfo};
  156. if (Package["accounts-base"]) {
  157. if (sandstormInfo.id) {
  158. // The user is logged into Sandstorm. Create a Meteor account for them, or find the
  159. // existing one, and record the user ID.
  160. var login = Package["accounts-base"].Accounts.updateOrCreateUserFromExternalService(
  161. "sandstorm", sandstormInfo, {profile: {name: sandstormInfo.name}});
  162. userInfo.userId = login.userId;
  163. } else {
  164. userInfo.userId = null;
  165. }
  166. } else {
  167. // Since the app isn't using regular Meteor accounts, we can define Meteor.userId()
  168. // however we want.
  169. userInfo.userId = sandstormInfo.id;
  170. }
  171. userInfo.sessionId = req.headers["x-sandstorm-session-id"] || null;
  172. userInfo.tabId = req.headers["x-sandstorm-tab-id"] || null;
  173. future.return(userInfo);
  174. res.writeHead(204, {});
  175. res.end();
  176. } catch (err) {
  177. res.writeHead(500, {
  178. "Content-Type": "text/plain"
  179. });
  180. res.end(err.stack);
  181. }
  182. });
  183. });
  184. }