Skip to content

Commit 98dc761

Browse files
committed
code review comments
1 parent 32f22c7 commit 98dc761

6 files changed

Lines changed: 86 additions & 21 deletions

File tree

app-client-starter-app/.github/workflows/ci.yml renamed to .github/workflows/ci.yml

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,18 @@ permissions:
99
contents: read
1010

1111
jobs:
12-
verify:
12+
app-client-starter-app:
1313
runs-on: ubuntu-latest
14+
defaults:
15+
run:
16+
working-directory: app-client-starter-app
1417
steps:
1518
- uses: actions/checkout@v4
1619
- uses: actions/setup-node@v4
1720
with:
1821
node-version: 22
1922
cache: npm
23+
cache-dependency-path: app-client-starter-app/package-lock.json
2024
- run: npm ci
2125
- run: npm test
2226
- run: npm run lint
Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
# Never upload the local TLS key, and let the platform install dependencies.
1+
# Never upload local secrets (the TLS key, .env, the development session key),
2+
# and let the platform install dependencies.
23
certs/
34
node_modules/
45
.env
6+
.session-key

‎app-client-starter-app/README.md‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ It's a small starter app called Draft Queue which covers key components of an ap
1212

1313
Use it as a starting point for your own integration. Clone it, configure it with your own app client, build new features on top, or share it with your AI coding agent as a reference.
1414

15-
📘 **Tutorial:** [Creating Buffer Client Apps](https://example.com/TODO-tutorial-url) walks through this example step by step, from registering an app client to deploying it.
1615

1716
## Prerequisites
1817

@@ -48,7 +47,7 @@ Use it as a starting point for your own integration. Clone it, configure it with
4847
| `BUFFER_CLIENT_ID` | Your app client ID from Buffer. |
4948
| `BUFFER_CLIENT_SECRET` | Required for a confidential client. Never expose it to the browser or commit it. |
5049
| `SESSION_SECRET` | At least 32 characters. Generate one with `openssl rand -hex 32`. Optional locally, required in production. |
51-
| `REDIRECT_URI` | Optional locally. If set, it must exactly match the redirect URI registered for your app client. |
50+
| `REDIRECT_URI` | Optional locally and on your Vercel production deployment. If set, it must exactly match the redirect URI registered for your app client. Vercel preview deployments have no default callback, so login is disabled on them unless you register the preview's `/callback` URL and set `REDIRECT_URI` for that environment. |
5251

5352
4. Generate a self-signed certificate for local HTTPS:
5453

‎app-client-starter-app/lib/app.js‎

Lines changed: 28 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import express from 'express'
22
import path from 'node:path'
3-
import { HttpError, REDIRECT_URI, withCause } from './config.js'
3+
import { HttpError, REDIRECT_URI, loginUnavailableReason, withCause } from './config.js'
44
import { readSession } from './session.js'
55
import {
66
ACCOUNT_QUERY,
@@ -46,7 +46,10 @@ const wrap = (handler) => async (req, res, next) => {
4646
}
4747
}
4848

49-
app.get('/auth/login', async (req, res) => {
49+
app.get('/auth/login', wrap(async (req, res) => {
50+
const unavailable = loginUnavailableReason(req.get('host'))
51+
if (unavailable) return res.redirect(`/?error=${encodeURIComponent(unavailable)}`)
52+
5053
const { verifier, challenge } = createPkcePair()
5154
const state = createState()
5255

@@ -56,9 +59,9 @@ app.get('/auth/login', async (req, res) => {
5659
await req.session.save()
5760

5861
res.redirect(buildAuthorizeUrl({ state, codeChallenge: challenge }))
59-
})
62+
}))
6063

61-
app.get('/callback', async (req, res) => {
64+
app.get('/callback', wrap(async (req, res) => {
6265
const { code, state, error, error_description: description } = req.query
6366
const pkce = req.session.pkce
6467
req.session.pkce = null // one-time values — discard either way
@@ -84,23 +87,34 @@ app.get('/callback', async (req, res) => {
8487
return res.status(403).send('Invalid state parameter: this callback did not come from a login this app started.')
8588
}
8689

90+
let tokens
8791
try {
8892
// The code is short-lived, so exchange it immediately.
89-
req.session.tokens = await exchangeCodeForTokens({ code, codeVerifier: pkce.codeVerifier })
90-
await req.session.save()
91-
res.redirect('/')
93+
tokens = await exchangeCodeForTokens({ code, codeVerifier: pkce.codeVerifier })
9294
} catch (err) {
9395
console.error(JSON.stringify({ event: 'oauth_token_exchange_failed', code: err.oauthError, message: err.message }))
9496
await req.session.save()
9597
const message = withCause('Buffer could not complete the connection. Check your client configuration.', err.message)
96-
res.redirect(`/?error=${encodeURIComponent(message)}`)
98+
return res.redirect(`/?error=${encodeURIComponent(message)}`)
9799
}
98-
})
99100

100-
app.post('/auth/logout', async (req, res) => {
101+
try {
102+
req.session.tokens = tokens
103+
await req.session.save()
104+
} catch (err) {
105+
// Saving can fail because of the tokens themselves (a sealed cookie that is
106+
// too large, say), so drop them before saving the cleared session.
107+
req.session.tokens = null
108+
await req.session.save()
109+
throw err
110+
}
111+
res.redirect('/')
112+
}))
113+
114+
app.post('/auth/logout', wrap(async (req, res) => {
101115
await req.session.destroy()
102116
res.json({ connected: false })
103-
})
117+
}))
104118

105119
app.get('/api/session', wrap(async (req, res) => {
106120
// redirectUri is echoed back for debugging: curl this endpoint to see the
@@ -167,7 +181,9 @@ app.post('/api/posts', wrap(async (req, res) => {
167181

168182
// Misconfiguration (a missing SESSION_SECRET, for instance) should read as a
169183
// clear message instead of an opaque platform 500.
170-
app.use((err, _req, res, _next) => {
184+
app.use((err, _req, res, next) => {
185+
// Too late for a clean response; let Express close the connection.
186+
if (res.headersSent) return next(err)
171187
console.error(JSON.stringify({ event: 'unhandled_request_error', name: err.name, message: err.message }))
172188
res.status(500).json({ error: withCause('Something went wrong. Please try again.', err.message) })
173189
})

‎app-client-starter-app/lib/config.js‎

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,17 @@ if (!CLIENT_ID) {
2727
export const CLIENT_SECRET = process.env.BUFFER_CLIENT_SECRET?.trim() || null
2828

2929
// OAuth redirect URIs must match what is registered with Buffer exactly.
30-
// On Vercel, default to the stable production domain — preview URLs change
31-
// every deploy and would never match a registered URI.
32-
function defaultRedirectUri() {
33-
const productionUrl = process.env.VERCEL_PROJECT_PRODUCTION_URL
34-
if (productionUrl) return `https://${productionUrl}/callback`
30+
// On Vercel, only the production deployment defaults to the stable production
31+
// domain. Vercel sets VERCEL_PROJECT_PRODUCTION_URL on previews too, but a
32+
// preview can't use that callback: the production host can't read the
33+
// preview's session cookie, so the PKCE verifier would be lost. Previews get no
34+
// default, and login stays off there unless REDIRECT_URI is set for them.
35+
export function defaultRedirectUri(env = process.env) {
36+
if (env.VERCEL_ENV) {
37+
return env.VERCEL_ENV === 'production' && env.VERCEL_PROJECT_PRODUCTION_URL
38+
? `https://${env.VERCEL_PROJECT_PRODUCTION_URL}/callback`
39+
: null
40+
}
3541
return `https://localhost:${PORT}/callback`
3642
}
3743

@@ -52,10 +58,27 @@ function sanitizeRedirectUri(value) {
5258
}
5359
}
5460

61+
// null means this deployment has no registered callback, so login is disabled.
5562
export const REDIRECT_URI = process.env.REDIRECT_URI
5663
? sanitizeRedirectUri(process.env.REDIRECT_URI)
5764
: defaultRedirectUri()
5865

66+
// The session cookie holding the PKCE verifier belongs to the host that started
67+
// the login, so the callback has to land on that same host. Returns why login
68+
// can't start from `host`, or null when it can.
69+
export function loginUnavailableReason(host, redirectUri = REDIRECT_URI) {
70+
if (!redirectUri) {
71+
return 'Login is disabled on this deployment: it has no registered callback. ' +
72+
'Register this deployment\'s /callback URL with your app client and set REDIRECT_URI to it, or use the production deployment.'
73+
}
74+
const callbackHost = new URL(redirectUri).host
75+
if (host !== callbackHost) {
76+
return `Login is only available at https://${callbackHost}, the host of the registered callback (${redirectUri}). ` +
77+
'Starting it from another host would lose the session that carries the login.'
78+
}
79+
return null
80+
}
81+
5982
// The OAuth flow spans two requests, so a key that changed on each boot would
6083
// break any login that straddled a restart. Persist the development one.
6184
const DEV_KEY_FILE = path.join(import.meta.dirname, '..', '.session-key')

‎app-client-starter-app/test/buffer.test.js‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ process.env.BUFFER_CLIENT_ID = 'test-client'
66
process.env.SESSION_SECRET = 'a'.repeat(32)
77
process.env.REDIRECT_URI = 'https://example.test/callback'
88

9+
const { defaultRedirectUri, loginUnavailableReason } = await import('../lib/config.js')
910
const { buildAuthorizeUrl, buildPostInput, createPkcePair, exchangeCodeForTokens, refreshTokens, requestTokens } = await import('../lib/buffer.js')
1011

1112
test('PKCE pairs use an S256 base64url challenge', () => {
@@ -108,3 +109,23 @@ test('error detail reaches a developer but never a production user', async () =>
108109
})
109110
assert.equal(output.trim(), 'Generic.')
110111
})
112+
113+
test('only the Vercel production deployment defaults to the production callback', () => {
114+
const productionUrl = 'app.example.test'
115+
assert.equal(
116+
defaultRedirectUri({ VERCEL_ENV: 'production', VERCEL_PROJECT_PRODUCTION_URL: productionUrl }),
117+
'https://app.example.test/callback',
118+
)
119+
// Vercel sets the production URL on previews too; it must not be used there.
120+
assert.equal(defaultRedirectUri({ VERCEL_ENV: 'preview', VERCEL_PROJECT_PRODUCTION_URL: productionUrl }), null)
121+
assert.equal(defaultRedirectUri({ VERCEL_ENV: 'development', VERCEL_PROJECT_PRODUCTION_URL: productionUrl }), null)
122+
assert.equal(defaultRedirectUri({}), 'https://localhost:3000/callback')
123+
})
124+
125+
test('login starts only on the host of the registered callback', () => {
126+
assert.equal(loginUnavailableReason('example.test', 'https://example.test/callback'), null)
127+
assert.equal(loginUnavailableReason('localhost:3000', 'https://localhost:3000/callback'), null)
128+
assert.match(loginUnavailableReason('app-git-branch.vercel.app', 'https://example.test/callback'), /only available at https:\/\/example\.test/)
129+
assert.match(loginUnavailableReason('127.0.0.1:3000', 'https://localhost:3000/callback'), /only available/)
130+
assert.match(loginUnavailableReason('app-git-branch.vercel.app', null), /disabled on this deployment/)
131+
})

0 commit comments

Comments
 (0)