pulse-hub 3.5.0 → 3.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/backend/.env.example +52 -52
  3. package/backend/agent.js +372 -372
  4. package/backend/cli.js +23 -1
  5. package/backend/emails/env-backup.html +52 -52
  6. package/backend/emails/invite.html +53 -53
  7. package/backend/lib/agent-rpc.js +72 -72
  8. package/backend/lib/async-route.js +17 -17
  9. package/backend/lib/authz/bootstrap.js +35 -35
  10. package/backend/lib/authz/catalog.js +291 -291
  11. package/backend/lib/authz/delegation.js +104 -104
  12. package/backend/lib/authz/effective.js +104 -104
  13. package/backend/lib/authz/engine.js +251 -251
  14. package/backend/lib/authz/index.js +134 -134
  15. package/backend/lib/authz/migrate.js +871 -871
  16. package/backend/lib/authz/mutate.js +87 -87
  17. package/backend/lib/authz/preview.js +327 -327
  18. package/backend/lib/authz/scope.js +282 -282
  19. package/backend/lib/env-mask.js +131 -131
  20. package/backend/lib/invite-helpers.js +83 -83
  21. package/backend/lib/invites.js +160 -160
  22. package/backend/lib/logs.js +244 -244
  23. package/backend/lib/metrics.js +249 -249
  24. package/backend/lib/relay-state.js +564 -564
  25. package/backend/lib/session.js +48 -48
  26. package/backend/middleware/authz.js +65 -65
  27. package/backend/public/assets/favicon.svg +6 -6
  28. package/backend/public/assets/index.js +1 -1
  29. package/backend/public/index.html +23 -24
  30. package/backend/routes/access.js +123 -123
  31. package/backend/routes/audit.js +41 -41
  32. package/backend/routes/auth.js +207 -207
  33. package/backend/routes/invites-public.js +91 -91
  34. package/backend/routes/invites.js +121 -121
  35. package/backend/routes/logs.js +68 -68
  36. package/backend/routes/metrics.js +76 -76
  37. package/backend/routes/policies.js +240 -240
  38. package/backend/routes/teams.js +221 -221
  39. package/backend/routes/users.js +100 -100
  40. package/backend/seed-admins.js +68 -68
  41. package/backend/server.js +106 -106
  42. package/backend/ws/agent-relay.js +159 -159
  43. package/package.json +1 -1
@@ -1,207 +1,207 @@
1
- // Operator sign-in: the static login page, logout, Google OAuth start+callback, and the
2
- // public auth-config probe Login.tsx needs before any session exists.
3
-
4
- const crypto = require('crypto');
5
- const express = require('express');
6
- const db = require('../lib/db');
7
- const googleAuth = require('../lib/auth-google');
8
- const invites = require('../lib/invites');
9
- const store = require('../lib/authz-store');
10
- const audit = require('../lib/audit');
11
- const { mutate } = require('../lib/authz/mutate');
12
- const { createSessionToken, parseCookies } = require('../lib/session');
13
- const { STATIC_FILES, serveStatic } = require('../lib/static-files');
14
- const { parseCombinedInviteToken } = require('../lib/invite-helpers');
15
- const config = require('../config');
16
-
17
- const router = express.Router();
18
-
19
- router.all('/login', (req, res) => {
20
- serveStatic(res, STATIC_FILES['/login']);
21
- });
22
-
23
- router.all('/logout', (req, res) => {
24
- res.writeHead(302, { 'Set-Cookie': 'session=; HttpOnly; Path=/; Max-Age=0', Location: 'login' });
25
- res.end();
26
- });
27
-
28
- // Public: Login.tsx needs to know whether to render "Sign in with Google" BEFORE any
29
- // session exists, so this can't live behind the authenticated /api/session-info.
30
- router.get('/api/auth-config', (req, res) => {
31
- res.writeHead(200, { 'Content-Type': 'application/json' });
32
- res.end(JSON.stringify({ googleEnabled: googleAuth.isEnabled() }));
33
- });
34
-
35
- router.get('/auth/google', (req, res) => {
36
- if (!googleAuth.isEnabled()) {
37
- res.writeHead(404);
38
- res.end('Google sign-in is not configured on this hub.');
39
- return;
40
- }
41
- const nonce = crypto.randomBytes(24).toString('hex');
42
- // An optional ?invite=<id>.<token> is carried through the state cookie (never the
43
- // URL after this redirect) so /auth/google/callback can tell "log an existing user
44
- // in" apart from "create a new user, but only because a validated invite says so".
45
- // HttpOnly + never echoed back to the client means this can't be tampered with
46
- // client-side between request and callback.
47
- const inviteParam = req.query.invite;
48
- const state = inviteParam ? `${nonce}:invite:${inviteParam}` : nonce;
49
- res.writeHead(302, {
50
- // SameSite=None, not Lax: the callback is a cross-site TOP-LEVEL navigation (the
51
- // browser lands here after leaving accounts.google.com), which a Strict cookie
52
- // would never be sent on. Lax was tried first since it's supposed to survive
53
- // top-level navigations, but WebKit (Safari/iOS, and therefore every iOS browser
54
- // incl. Chrome-on-iOS) has a long-standing bug where a SameSite=Lax cookie isn't
55
- // reliably sent on the FIRST load after a redirect chain like this one
56
- // (bugs.webkit.org #219650) — the state cookie went missing, the state check
57
- // below failed, and every mobile sign-in got bounced to /login?error=oauth
58
- // looking like "account not linked". None; Secure sidesteps that entirely
59
- // (always sent cross-site, as long as HTTPS — already required here) and is the
60
- // standard fix for short-lived OAuth state cookies like this one. (The operator
61
- // session cookie set further down, once the callback succeeds, hits basically
62
- // the same WebKit quirk one hop later — see the comment there.)
63
- 'Set-Cookie': `oauth_state=${state}; HttpOnly; Path=/; Max-Age=300; SameSite=None; Secure`,
64
- Location: googleAuth.buildAuthorizationUrl(state, 'openid email profile'),
65
- });
66
- res.end();
67
- });
68
-
69
- router.get('/auth/google/callback', async (req, res) => {
70
- const expectedState = parseCookies(req)['oauth_state'];
71
- const returnedState = req.query.state;
72
- const code = req.query.code;
73
- const clearStateCookie = 'oauth_state=; HttpOnly; Path=/; Max-Age=0';
74
- if (!googleAuth.isEnabled() || !code || !expectedState || expectedState !== returnedState) {
75
- // Relative to /auth/google/callback, so '../../' is needed to reach the site root
76
- // (see relative-paths-under-subpath.md) — a bare 'login' would resolve under
77
- // /auth/google/ instead.
78
- res.writeHead(302, { 'Set-Cookie': clearStateCookie, Location: '../../login?error=oauth' });
79
- res.end();
80
- return;
81
- }
82
- const stateParts = expectedState.split(':'); // "<nonce>:invite:<id>.<token>" or just "<nonce>"
83
- const inviteParam = stateParts[1] === 'invite' ? stateParts[2] : null;
84
- try {
85
- const tokens = await googleAuth.exchangeCodeForTokens(code);
86
- const identity = await googleAuth.verifyIdToken(tokens.id_token);
87
-
88
- // Find-or-create policy: a plain Google login only ever signs in an ALREADY
89
- // KNOWN user (matched by google_id, or by a verified email matching an existing
90
- // local account, in which case the Google identity is linked for next time). It
91
- // deliberately does NOT self-provision a brand-new user — that would let any
92
- // Google account claim full access to a private monitoring hub.
93
- let user = db.getUserByGoogleId(identity.googleId);
94
- if (!user) {
95
- const existingByEmail = identity.email ? db.getUserByEmail(identity.email) : null;
96
- if (existingByEmail)
97
- user = db.linkGoogleIdToUser(existingByEmail.id, identity.googleId, identity.email);
98
- }
99
-
100
- // The ONE exception to "don't self-provision": a validated, still-pending invite
101
- // whose email exactly matches this Google account's (Google-verified) email. This
102
- // is the only path that can create a brand-new user via Google sign-in.
103
- if (!user && inviteParam) {
104
- const parsed = parseCombinedInviteToken(inviteParam);
105
- const invite = parsed && invites.verifyInviteToken(parsed.inviteId, parsed.token);
106
- if (invite && identity.email && invite.email.toLowerCase() === identity.email.toLowerCase()) {
107
- // The invite's teams are applied below, for every pending invite for this email.
108
- user = db.createGoogleUser({
109
- googleId: identity.googleId,
110
- email: identity.email,
111
- });
112
- }
113
- }
114
-
115
- if (!user) {
116
- audit.record(
117
- {
118
- action: 'login.denied',
119
- targetType: 'user',
120
- outcome: 'denied',
121
- summary: `Sign-in denied for ${identity.email || 'unknown account'}`,
122
- actor: { email: identity.email || null },
123
- },
124
- req,
125
- );
126
- res.writeHead(302, { 'Set-Cookie': clearStateCookie, Location: '../../login?error=oauth' });
127
- res.end();
128
- return;
129
- }
130
-
131
- // Not scoped to just the invite that was clicked above: any pending invite for
132
- // this email is moot now that they have a working account, however they got it
133
- // (an existing account, a seed-admins.js row, or this exact invite) — see
134
- // autoAcceptPendingInvitesForEmail's comment in lib/invites.js.
135
- if (identity.email) {
136
- // Join the teams each pending invite carried (they were delegation-checked when the
137
- // invite was sent), then close those invites out.
138
- const pending = invites.getPendingInvitesForEmail(identity.email);
139
- const teamIds = [...new Set(pending.flatMap((i) => invites.parseTeamIds(i.team_ids)))].filter(
140
- (id) => store.getTeam(id),
141
- );
142
- if (teamIds.length > 0) {
143
- mutate(() => {
144
- for (const teamId of teamIds) store.addTeamMember(teamId, user.id, user.id);
145
- });
146
- }
147
- for (const inv of pending) {
148
- audit.record(
149
- {
150
- action: 'invite.accepted',
151
- targetType: 'invite',
152
- targetId: inv.id,
153
- outcome: 'succeeded',
154
- summary: `${identity.email} accepted an invite`,
155
- actor: { id: user.id, email: user.email },
156
- },
157
- req,
158
- );
159
- }
160
- invites.autoAcceptPendingInvitesForEmail(identity.email);
161
- }
162
-
163
- // Refreshed on every login, not just the first — a Google avatar can change, and
164
- // there's no other event that would ever pick that up otherwise.
165
- if (identity.picture) user = db.setUserPicture(user.id, identity.picture);
166
-
167
- audit.record(
168
- {
169
- action: 'login.succeeded',
170
- targetType: 'user',
171
- targetId: user.id,
172
- outcome: 'succeeded',
173
- summary: `${user.email || user.id} signed in`,
174
- actor: { id: user.id, email: user.email },
175
- },
176
- req,
177
- );
178
- const token = createSessionToken(user);
179
- res.writeHead(302, {
180
- // SameSite=Lax, not Strict: this cookie is set on the response to the OAuth
181
- // callback itself — the same request that just landed here via a cross-site
182
- // redirect from accounts.google.com — and needs to survive the very next hop
183
- // (our own 302 to '../..', below). A Strict cookie doesn't reliably make it
184
- // through that on mobile (the same WebKit redirect-chain bug as oauth_state
185
- // above — this was the actual bug behind "mobile Google sign-in redirects to
186
- // /login#/login after picking an account": the session cookie never made it
187
- // to the browser, so the very next page load found no session and bounced
188
- // back to login). Lax is enough here (unlike oauth_state, this cookie only
189
- // ever needs to be sent on requests to our own site from then on) and, unlike
190
- // None, still gets CSRF protection on cross-site requests for the life of the
191
- // session.
192
- 'Set-Cookie': [
193
- clearStateCookie,
194
- `session=${token}; HttpOnly; Path=/; Max-Age=${config.SESSION_MAX_AGE_MS / 1000}; SameSite=Lax; Secure`,
195
- ],
196
- // '../..' from /auth/google/callback, not '.' — '.' resolves to /auth/google/,
197
- // which has no route (see relative-paths-under-subpath.md).
198
- Location: '../..',
199
- });
200
- res.end();
201
- } catch (e) {
202
- res.writeHead(302, { 'Set-Cookie': clearStateCookie, Location: '../../login?error=oauth' });
203
- res.end();
204
- }
205
- });
206
-
207
- module.exports = router;
1
+ // Operator sign-in: the static login page, logout, Google OAuth start+callback, and the
2
+ // public auth-config probe Login.tsx needs before any session exists.
3
+
4
+ const crypto = require('crypto');
5
+ const express = require('express');
6
+ const db = require('../lib/db');
7
+ const googleAuth = require('../lib/auth-google');
8
+ const invites = require('../lib/invites');
9
+ const store = require('../lib/authz-store');
10
+ const audit = require('../lib/audit');
11
+ const { mutate } = require('../lib/authz/mutate');
12
+ const { createSessionToken, parseCookies } = require('../lib/session');
13
+ const { STATIC_FILES, serveStatic } = require('../lib/static-files');
14
+ const { parseCombinedInviteToken } = require('../lib/invite-helpers');
15
+ const config = require('../config');
16
+
17
+ const router = express.Router();
18
+
19
+ router.all('/login', (req, res) => {
20
+ serveStatic(res, STATIC_FILES['/login']);
21
+ });
22
+
23
+ router.all('/logout', (req, res) => {
24
+ res.writeHead(302, { 'Set-Cookie': 'session=; HttpOnly; Path=/; Max-Age=0', Location: 'login' });
25
+ res.end();
26
+ });
27
+
28
+ // Public: Login.tsx needs to know whether to render "Sign in with Google" BEFORE any
29
+ // session exists, so this can't live behind the authenticated /api/session-info.
30
+ router.get('/api/auth-config', (req, res) => {
31
+ res.writeHead(200, { 'Content-Type': 'application/json' });
32
+ res.end(JSON.stringify({ googleEnabled: googleAuth.isEnabled() }));
33
+ });
34
+
35
+ router.get('/auth/google', (req, res) => {
36
+ if (!googleAuth.isEnabled()) {
37
+ res.writeHead(404);
38
+ res.end('Google sign-in is not configured on this hub.');
39
+ return;
40
+ }
41
+ const nonce = crypto.randomBytes(24).toString('hex');
42
+ // An optional ?invite=<id>.<token> is carried through the state cookie (never the
43
+ // URL after this redirect) so /auth/google/callback can tell "log an existing user
44
+ // in" apart from "create a new user, but only because a validated invite says so".
45
+ // HttpOnly + never echoed back to the client means this can't be tampered with
46
+ // client-side between request and callback.
47
+ const inviteParam = req.query.invite;
48
+ const state = inviteParam ? `${nonce}:invite:${inviteParam}` : nonce;
49
+ res.writeHead(302, {
50
+ // SameSite=None, not Lax: the callback is a cross-site TOP-LEVEL navigation (the
51
+ // browser lands here after leaving accounts.google.com), which a Strict cookie
52
+ // would never be sent on. Lax was tried first since it's supposed to survive
53
+ // top-level navigations, but WebKit (Safari/iOS, and therefore every iOS browser
54
+ // incl. Chrome-on-iOS) has a long-standing bug where a SameSite=Lax cookie isn't
55
+ // reliably sent on the FIRST load after a redirect chain like this one
56
+ // (bugs.webkit.org #219650) — the state cookie went missing, the state check
57
+ // below failed, and every mobile sign-in got bounced to /login?error=oauth
58
+ // looking like "account not linked". None; Secure sidesteps that entirely
59
+ // (always sent cross-site, as long as HTTPS — already required here) and is the
60
+ // standard fix for short-lived OAuth state cookies like this one. (The operator
61
+ // session cookie set further down, once the callback succeeds, hits basically
62
+ // the same WebKit quirk one hop later — see the comment there.)
63
+ 'Set-Cookie': `oauth_state=${state}; HttpOnly; Path=/; Max-Age=300; SameSite=None; Secure`,
64
+ Location: googleAuth.buildAuthorizationUrl(state, 'openid email profile'),
65
+ });
66
+ res.end();
67
+ });
68
+
69
+ router.get('/auth/google/callback', async (req, res) => {
70
+ const expectedState = parseCookies(req)['oauth_state'];
71
+ const returnedState = req.query.state;
72
+ const code = req.query.code;
73
+ const clearStateCookie = 'oauth_state=; HttpOnly; Path=/; Max-Age=0';
74
+ if (!googleAuth.isEnabled() || !code || !expectedState || expectedState !== returnedState) {
75
+ // Relative to /auth/google/callback, so '../../' is needed to reach the site root
76
+ // (see relative-paths-under-subpath.md) — a bare 'login' would resolve under
77
+ // /auth/google/ instead.
78
+ res.writeHead(302, { 'Set-Cookie': clearStateCookie, Location: '../../login?error=oauth' });
79
+ res.end();
80
+ return;
81
+ }
82
+ const stateParts = expectedState.split(':'); // "<nonce>:invite:<id>.<token>" or just "<nonce>"
83
+ const inviteParam = stateParts[1] === 'invite' ? stateParts[2] : null;
84
+ try {
85
+ const tokens = await googleAuth.exchangeCodeForTokens(code);
86
+ const identity = await googleAuth.verifyIdToken(tokens.id_token);
87
+
88
+ // Find-or-create policy: a plain Google login only ever signs in an ALREADY
89
+ // KNOWN user (matched by google_id, or by a verified email matching an existing
90
+ // local account, in which case the Google identity is linked for next time). It
91
+ // deliberately does NOT self-provision a brand-new user — that would let any
92
+ // Google account claim full access to a private monitoring hub.
93
+ let user = db.getUserByGoogleId(identity.googleId);
94
+ if (!user) {
95
+ const existingByEmail = identity.email ? db.getUserByEmail(identity.email) : null;
96
+ if (existingByEmail)
97
+ user = db.linkGoogleIdToUser(existingByEmail.id, identity.googleId, identity.email);
98
+ }
99
+
100
+ // The ONE exception to "don't self-provision": a validated, still-pending invite
101
+ // whose email exactly matches this Google account's (Google-verified) email. This
102
+ // is the only path that can create a brand-new user via Google sign-in.
103
+ if (!user && inviteParam) {
104
+ const parsed = parseCombinedInviteToken(inviteParam);
105
+ const invite = parsed && invites.verifyInviteToken(parsed.inviteId, parsed.token);
106
+ if (invite && identity.email && invite.email.toLowerCase() === identity.email.toLowerCase()) {
107
+ // The invite's teams are applied below, for every pending invite for this email.
108
+ user = db.createGoogleUser({
109
+ googleId: identity.googleId,
110
+ email: identity.email,
111
+ });
112
+ }
113
+ }
114
+
115
+ if (!user) {
116
+ audit.record(
117
+ {
118
+ action: 'login.denied',
119
+ targetType: 'user',
120
+ outcome: 'denied',
121
+ summary: `Sign-in denied for ${identity.email || 'unknown account'}`,
122
+ actor: { email: identity.email || null },
123
+ },
124
+ req,
125
+ );
126
+ res.writeHead(302, { 'Set-Cookie': clearStateCookie, Location: '../../login?error=oauth' });
127
+ res.end();
128
+ return;
129
+ }
130
+
131
+ // Not scoped to just the invite that was clicked above: any pending invite for
132
+ // this email is moot now that they have a working account, however they got it
133
+ // (an existing account, a seed-admins.js row, or this exact invite) — see
134
+ // autoAcceptPendingInvitesForEmail's comment in lib/invites.js.
135
+ if (identity.email) {
136
+ // Join the teams each pending invite carried (they were delegation-checked when the
137
+ // invite was sent), then close those invites out.
138
+ const pending = invites.getPendingInvitesForEmail(identity.email);
139
+ const teamIds = [...new Set(pending.flatMap((i) => invites.parseTeamIds(i.team_ids)))].filter(
140
+ (id) => store.getTeam(id),
141
+ );
142
+ if (teamIds.length > 0) {
143
+ mutate(() => {
144
+ for (const teamId of teamIds) store.addTeamMember(teamId, user.id, user.id);
145
+ });
146
+ }
147
+ for (const inv of pending) {
148
+ audit.record(
149
+ {
150
+ action: 'invite.accepted',
151
+ targetType: 'invite',
152
+ targetId: inv.id,
153
+ outcome: 'succeeded',
154
+ summary: `${identity.email} accepted an invite`,
155
+ actor: { id: user.id, email: user.email },
156
+ },
157
+ req,
158
+ );
159
+ }
160
+ invites.autoAcceptPendingInvitesForEmail(identity.email);
161
+ }
162
+
163
+ // Refreshed on every login, not just the first — a Google avatar can change, and
164
+ // there's no other event that would ever pick that up otherwise.
165
+ if (identity.picture) user = db.setUserPicture(user.id, identity.picture);
166
+
167
+ audit.record(
168
+ {
169
+ action: 'login.succeeded',
170
+ targetType: 'user',
171
+ targetId: user.id,
172
+ outcome: 'succeeded',
173
+ summary: `${user.email || user.id} signed in`,
174
+ actor: { id: user.id, email: user.email },
175
+ },
176
+ req,
177
+ );
178
+ const token = createSessionToken(user);
179
+ res.writeHead(302, {
180
+ // SameSite=Lax, not Strict: this cookie is set on the response to the OAuth
181
+ // callback itself — the same request that just landed here via a cross-site
182
+ // redirect from accounts.google.com — and needs to survive the very next hop
183
+ // (our own 302 to '../..', below). A Strict cookie doesn't reliably make it
184
+ // through that on mobile (the same WebKit redirect-chain bug as oauth_state
185
+ // above — this was the actual bug behind "mobile Google sign-in redirects to
186
+ // /login#/login after picking an account": the session cookie never made it
187
+ // to the browser, so the very next page load found no session and bounced
188
+ // back to login). Lax is enough here (unlike oauth_state, this cookie only
189
+ // ever needs to be sent on requests to our own site from then on) and, unlike
190
+ // None, still gets CSRF protection on cross-site requests for the life of the
191
+ // session.
192
+ 'Set-Cookie': [
193
+ clearStateCookie,
194
+ `session=${token}; HttpOnly; Path=/; Max-Age=${config.SESSION_MAX_AGE_MS / 1000}; SameSite=Lax; Secure`,
195
+ ],
196
+ // '../..' from /auth/google/callback, not '.' — '.' resolves to /auth/google/,
197
+ // which has no route (see relative-paths-under-subpath.md).
198
+ Location: '../..',
199
+ });
200
+ res.end();
201
+ } catch (e) {
202
+ res.writeHead(302, { 'Set-Cookie': clearStateCookie, Location: '../../login?error=oauth' });
203
+ res.end();
204
+ }
205
+ });
206
+
207
+ module.exports = router;
@@ -1,91 +1,91 @@
1
- // Invite accept flow: public, since an invitee has no session yet.
2
-
3
- const express = require('express');
4
- const db = require('../lib/db');
5
- const googleAuth = require('../lib/auth-google');
6
- const invites = require('../lib/invites');
7
- const store = require('../lib/authz-store');
8
- const { readJsonBody } = require('../lib/http-helpers');
9
- const { parseCombinedInviteToken, renderInviteResendPage } = require('../lib/invite-helpers');
10
-
11
- const router = express.Router();
12
-
13
- router.get('/api/invites/info', (req, res) => {
14
- const parsed = parseCombinedInviteToken(req.query.token);
15
- const invite = parsed && invites.verifyInviteToken(parsed.inviteId, parsed.token);
16
- if (!invite) {
17
- res.writeHead(404, { 'Content-Type': 'application/json' });
18
- res.end(JSON.stringify({ error: 'This invite link is invalid, expired, or already used.' }));
19
- return;
20
- }
21
- const invitedBy = db.getUserById(invite.invited_by_user_id);
22
- res.writeHead(200, { 'Content-Type': 'application/json' });
23
- res.end(
24
- JSON.stringify({
25
- email: invite.email,
26
- invitedByLabel: (invitedBy && (invitedBy.email || invitedBy.username)) || 'a Pulse user',
27
- googleEnabled: googleAuth.isEnabled(),
28
- teamNames: invites
29
- .parseTeamIds(invite.team_ids)
30
- .map((id) => store.getTeam(id))
31
- .filter(Boolean)
32
- .map((t) => t.name),
33
- }),
34
- );
35
- });
36
-
37
- router.post('/api/invites/accept', async (req, res) => {
38
- const body = await readJsonBody(req);
39
- const parsed = parseCombinedInviteToken(body.token);
40
- const invite = parsed && invites.verifyInviteToken(parsed.inviteId, parsed.token);
41
- if (!invite) {
42
- res.writeHead(404, { 'Content-Type': 'application/json' });
43
- res.end(JSON.stringify({ error: 'This invite link is invalid, expired, or already used.' }));
44
- return;
45
- }
46
- // Sign-in is Google-only (password login was removed — see docs/auth-model.md), so
47
- // accepting an invite always means "sign in with Google" — this route stays only as
48
- // a friendly error for anyone whose email client posts to it directly (or an old
49
- // bookmarked/cached page); the frontend never calls it anymore.
50
- res.writeHead(400, { 'Content-Type': 'application/json' });
51
- res.end(JSON.stringify({ error: 'Sign in with Google to accept this invite.' }));
52
- });
53
-
54
- // Public GET, opened directly from the "trouble with this link?" button in the invite
55
- // email itself — an email client can only follow a plain link, never fire an
56
- // authenticated fetch. Deliberately ignores expiry (verifyPendingInviteTokenIgnoringExpiry,
57
- // not verifyInviteToken) since an expired link is exactly the case this exists to
58
- // handle; only records that a resend was requested (surfaced next to the invite on the
59
- // Account page's Team tab) rather than resending automatically, so the inviter stays in
60
- // control of who actually gets a new invite.
61
- router.get('/invite-resend', (req, res) => {
62
- const parsed = parseCombinedInviteToken(req.query.token);
63
- const invite =
64
- parsed && invites.verifyPendingInviteTokenIgnoringExpiry(parsed.inviteId, parsed.token);
65
- res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
66
- if (!invite) {
67
- res.end(
68
- renderInviteResendPage(
69
- 'Link not found',
70
- 'This invite link is invalid or no longer active. Ask whoever invited you to send a new one.',
71
- ),
72
- );
73
- return;
74
- }
75
- invites.markResendRequested(invite.id);
76
- const invitedBy = db.getUserById(invite.invited_by_user_id);
77
- const invitedByLabel =
78
- (invitedBy && (invitedBy.email || invitedBy.username)) || 'the person who invited you';
79
- const safeLabel = invitedByLabel.replace(
80
- /[&<>"']/g,
81
- (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c],
82
- );
83
- res.end(
84
- renderInviteResendPage(
85
- 'Request sent',
86
- `We've let ${safeLabel} know this invite link isn't working for you. They'll be able to send a new one from Pulse.`,
87
- ),
88
- );
89
- });
90
-
91
- module.exports = router;
1
+ // Invite accept flow: public, since an invitee has no session yet.
2
+
3
+ const express = require('express');
4
+ const db = require('../lib/db');
5
+ const googleAuth = require('../lib/auth-google');
6
+ const invites = require('../lib/invites');
7
+ const store = require('../lib/authz-store');
8
+ const { readJsonBody } = require('../lib/http-helpers');
9
+ const { parseCombinedInviteToken, renderInviteResendPage } = require('../lib/invite-helpers');
10
+
11
+ const router = express.Router();
12
+
13
+ router.get('/api/invites/info', (req, res) => {
14
+ const parsed = parseCombinedInviteToken(req.query.token);
15
+ const invite = parsed && invites.verifyInviteToken(parsed.inviteId, parsed.token);
16
+ if (!invite) {
17
+ res.writeHead(404, { 'Content-Type': 'application/json' });
18
+ res.end(JSON.stringify({ error: 'This invite link is invalid, expired, or already used.' }));
19
+ return;
20
+ }
21
+ const invitedBy = db.getUserById(invite.invited_by_user_id);
22
+ res.writeHead(200, { 'Content-Type': 'application/json' });
23
+ res.end(
24
+ JSON.stringify({
25
+ email: invite.email,
26
+ invitedByLabel: (invitedBy && (invitedBy.email || invitedBy.username)) || 'a Pulse user',
27
+ googleEnabled: googleAuth.isEnabled(),
28
+ teamNames: invites
29
+ .parseTeamIds(invite.team_ids)
30
+ .map((id) => store.getTeam(id))
31
+ .filter(Boolean)
32
+ .map((t) => t.name),
33
+ }),
34
+ );
35
+ });
36
+
37
+ router.post('/api/invites/accept', async (req, res) => {
38
+ const body = await readJsonBody(req);
39
+ const parsed = parseCombinedInviteToken(body.token);
40
+ const invite = parsed && invites.verifyInviteToken(parsed.inviteId, parsed.token);
41
+ if (!invite) {
42
+ res.writeHead(404, { 'Content-Type': 'application/json' });
43
+ res.end(JSON.stringify({ error: 'This invite link is invalid, expired, or already used.' }));
44
+ return;
45
+ }
46
+ // Sign-in is Google-only (password login was removed — see docs/auth-model.md), so
47
+ // accepting an invite always means "sign in with Google" — this route stays only as
48
+ // a friendly error for anyone whose email client posts to it directly (or an old
49
+ // bookmarked/cached page); the frontend never calls it anymore.
50
+ res.writeHead(400, { 'Content-Type': 'application/json' });
51
+ res.end(JSON.stringify({ error: 'Sign in with Google to accept this invite.' }));
52
+ });
53
+
54
+ // Public GET, opened directly from the "trouble with this link?" button in the invite
55
+ // email itself — an email client can only follow a plain link, never fire an
56
+ // authenticated fetch. Deliberately ignores expiry (verifyPendingInviteTokenIgnoringExpiry,
57
+ // not verifyInviteToken) since an expired link is exactly the case this exists to
58
+ // handle; only records that a resend was requested (surfaced next to the invite on the
59
+ // Account page's Team tab) rather than resending automatically, so the inviter stays in
60
+ // control of who actually gets a new invite.
61
+ router.get('/invite-resend', (req, res) => {
62
+ const parsed = parseCombinedInviteToken(req.query.token);
63
+ const invite =
64
+ parsed && invites.verifyPendingInviteTokenIgnoringExpiry(parsed.inviteId, parsed.token);
65
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
66
+ if (!invite) {
67
+ res.end(
68
+ renderInviteResendPage(
69
+ 'Link not found',
70
+ 'This invite link is invalid or no longer active. Ask whoever invited you to send a new one.',
71
+ ),
72
+ );
73
+ return;
74
+ }
75
+ invites.markResendRequested(invite.id);
76
+ const invitedBy = db.getUserById(invite.invited_by_user_id);
77
+ const invitedByLabel =
78
+ (invitedBy && (invitedBy.email || invitedBy.username)) || 'the person who invited you';
79
+ const safeLabel = invitedByLabel.replace(
80
+ /[&<>"']/g,
81
+ (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c],
82
+ );
83
+ res.end(
84
+ renderInviteResendPage(
85
+ 'Request sent',
86
+ `We've let ${safeLabel} know this invite link isn't working for you. They'll be able to send a new one from Pulse.`,
87
+ ),
88
+ );
89
+ });
90
+
91
+ module.exports = router;