From 37573bfa3e1710c47a665e57b725d73c07fa70ac Mon Sep 17 00:00:00 2001 From: Jamie Ruderman Date: Wed, 7 Oct 2026 15:51:17 -0700 Subject: [PATCH 1/4] feat(amplify): PR previews sign in on dev as remoteit_portal, with their exact callbacks registered while open --- .github/scripts/preview-callbacks.mjs | 106 ++++++++++++++++++++++++ .github/workflows/preview-callbacks.yml | 49 +++++++++++ amplify.yml | 18 ++++ readme.md | 5 ++ scripts/amplify-preview-env.sh | 12 +++ 5 files changed, 190 insertions(+) create mode 100644 .github/scripts/preview-callbacks.mjs create mode 100644 .github/workflows/preview-callbacks.yml create mode 100644 amplify.yml create mode 100644 scripts/amplify-preview-env.sh diff --git a/.github/scripts/preview-callbacks.mjs b/.github/scripts/preview-callbacks.mjs new file mode 100644 index 000000000..ac3f884b0 --- /dev/null +++ b/.github/scripts/preview-callbacks.mjs @@ -0,0 +1,106 @@ +// Keeps remoteit_portal's preview callbacks on the dev login server equal to the open PRs Amplify +// previews. Every other entry belongs to the registry Terraform (authentication +// tf-permitteer-registry) and stays in place. +import crypto from 'node:crypto' +import { pathToFileURL } from 'node:url' + +const ISSUER = 'https://login.dev.remote.it' +const CLIENT_ID = 'remoteit_portal' +const OPERATOR_ID = 'svc_preview_callbacks' +const PREVIEW_HOST = 'd20k671nqqv4kl.amplifyapp.com' +// The Amplify branches with pull request previews turned on. +const PREVIEW_BASES = ['main', 'release'] + +const PREVIEW_URI = new RegExp(`^https://pr-\\d+\\.${PREVIEW_HOST.replaceAll('.', '\\.')}/`) +const previewUri = (pull, path) => `https://pr-${pull}.${PREVIEW_HOST}/${path}` + +export async function adminToken(pem, clientId = OPERATOR_ID) { + const key = crypto.createPrivateKey(pem) + const jwk = crypto.createPublicKey(key).export({ format: 'jwk' }) + const kid = crypto + .createHash('sha256') + .update(JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y })) + .digest('base64url') + .slice(0, 16) + const encode = value => Buffer.from(JSON.stringify(value)).toString('base64url') + const now = Math.floor(Date.now() / 1000) + const signing = `${encode({ alg: 'ES256', kid })}.${encode({ + iss: clientId, + sub: clientId, + aud: ISSUER, + iat: now, + exp: now + 120, + jti: crypto.randomUUID(), + })}` + const signature = crypto.sign('sha256', Buffer.from(signing), { key, dsaEncoding: 'ieee-p1363' }) + const response = await fetch(`${ISSUER}/token`, { + method: 'POST', + headers: { 'content-type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ + grant_type: 'client_credentials', + client_id: clientId, + client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer', + client_assertion: `${signing}.${signature.toString('base64url')}`, + resource: `${ISSUER}/admin/api`, + }), + }) + const body = await response.json() + if (!body.access_token) throw new Error(`token: ${response.status} ${JSON.stringify(body)}`) + return body.access_token +} + +export async function previewPulls(repo, token) { + const pulls = [] + for (let page = 1; ; page++) { + const response = await fetch(`https://api.github.com/repos/${repo}/pulls?state=open&per_page=100&page=${page}`, { + headers: { authorization: `Bearer ${token}`, accept: 'application/vnd.github+json' }, + }) + if (!response.ok) throw new Error(`pulls: ${response.status} ${await response.text()}`) + const batch = await response.json() + // A fork's PR is a stranger's code on a preview URL, so it never gets a callback. + pulls.push(...batch.filter(p => p.head.repo?.full_name === repo && PREVIEW_BASES.includes(p.base.ref))) + if (batch.length < 100) return pulls.map(p => p.number).sort((a, b) => a - b) + } +} + +export async function portal(token, method = 'GET', body) { + const response = await fetch(`${ISSUER}/admin/api/clients/${CLIENT_ID}`, { + method, + headers: { authorization: `Bearer ${token}`, ...(body && { 'content-type': 'application/json' }) }, + body: body && JSON.stringify(body), + }) + if (!response.ok) throw new Error(`${method} ${CLIENT_ID}: ${response.status} ${await response.text()}`) + return response.json() +} + +export function desired(client, pulls) { + const withPreviews = (uris = [], path) => [ + ...uris.filter(uri => !PREVIEW_URI.test(uri)), + ...pulls.map(pull => previewUri(pull, path)), + ] + return { + redirectUris: withPreviews(client.redirectUris, 'authCallback'), + postLogoutRedirectUris: withPreviews(client.postLogoutRedirectUris, 'signoutCallback'), + } +} + +export function changes(client, wanted) { + return Object.entries(wanted).flatMap(([field, uris]) => [ + ...uris.filter(uri => !client[field]?.includes(uri)).map(uri => `+ ${field} ${uri}`), + ...(client[field] ?? []).filter(uri => !uris.includes(uri)).map(uri => `- ${field} ${uri}`), + ]) +} + +if (import.meta.url === pathToFileURL(process.argv[1]).href) { + const pulls = await previewPulls(process.env.GITHUB_REPOSITORY, process.env.GITHUB_TOKEN) + const token = await adminToken(process.env.PREVIEW_CALLBACKS_KEY) + const client = await portal(token) + const wanted = desired(client, pulls) + const diff = changes(client, wanted) + console.log(`Open previews: ${pulls.map(pull => `#${pull}`).join(' ') || 'none'}`) + if (!diff.length) console.log(`${CLIENT_ID} is up to date.`) + else { + await portal(token, 'PATCH', wanted) + console.log(diff.join('\n')) + } +} diff --git a/.github/workflows/preview-callbacks.yml b/.github/workflows/preview-callbacks.yml new file mode 100644 index 000000000..0d1aa1a23 --- /dev/null +++ b/.github/workflows/preview-callbacks.yml @@ -0,0 +1,49 @@ +# Amplify serves each PR at https://pr-.d20k671nqqv4kl.amplifyapp.com, signed in on dev as +# remoteit_portal, which accepts only exactly registered redirect URIs. This keeps that client's +# preview callbacks equal to the open PRs (authentication tf-permitteer-registry/README.md). +name: Preview callbacks + +on: + pull_request: + types: [opened, reopened, closed] + branches: [main, release] + schedule: + - cron: '23 * * * *' + workflow_dispatch: + +permissions: {} + +jobs: + # The key's environment admits runs on main only, so a PR asks main to reconcile. Dependabot's + # token cannot dispatch; the hourly run picks its PRs up. + request: + if: >- + github.event_name == 'pull_request' && + github.event.pull_request.head.repo.full_name == github.repository && + github.actor != 'dependabot[bot]' + runs-on: ubuntu-latest + permissions: + actions: write + steps: + - run: gh workflow run preview-callbacks.yml --repo "$GITHUB_REPOSITORY" --ref main + env: + GH_TOKEN: ${{ github.token }} + + reconcile: + if: github.event_name != 'pull_request' + runs-on: ubuntu-latest + environment: preview-callbacks + concurrency: + group: preview-callbacks + permissions: + contents: read + pull-requests: read + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version-file: .nvmrc + - run: node .github/scripts/preview-callbacks.mjs + env: + GITHUB_TOKEN: ${{ github.token }} + PREVIEW_CALLBACKS_KEY: ${{ secrets.PREVIEW_CALLBACKS_KEY }} diff --git a/amplify.yml b/amplify.yml new file mode 100644 index 000000000..9162b57b1 --- /dev/null +++ b/amplify.yml @@ -0,0 +1,18 @@ +version: 1 +frontend: + phases: + preBuild: + commands: + - npm config set "@fortawesome:registry" https://npm.fontawesome.com/ + - npm config set "//npm.fontawesome.com/:_authToken" $FONT_AWESOME_AUTH_TOKEN + - npm install + build: + commands: + - if [ -n "$AWS_PULL_REQUEST_ID" ]; then . ./scripts/amplify-preview-env.sh; fi; npm run build-frontend + artifacts: + baseDirectory: frontend/build + files: + - '**/*' + cache: + paths: + - node_modules/**/* diff --git a/readme.md b/readme.md index b9ac37f63..128b8321a 100644 --- a/readme.md +++ b/readme.md @@ -122,6 +122,11 @@ Leave `VITE_OAUTH_CLIENT_ID` as `remoteit_desktop` locally. Redirect URIs are re branch config makes authorize fail with a 400. `remoteit_desktop` carries both `http://localhost:3003/authCallback` and `remoteit://authCallback` (the Electron deep link). +PR previews (`https://pr-.d20k671nqqv4kl.amplifyapp.com`) build on the dev stage as +`remoteit_portal` (`amplify.yml` sources `scripts/amplify-preview-env.sh`). The Preview callbacks +workflow registers each open PR's exact callbacks and removes them when it closes. A PR from a fork +gets none, so its preview cannot sign in. + Browse to `http://localhost:3003` exactly. `npm start` binds `0.0.0.0`, but reaching the app over a LAN IP is a non-secure origin, where `crypto.subtle` is unavailable and the DPoP proofs every token call carries silently degrade. diff --git a/scripts/amplify-preview-env.sh b/scripts/amplify-preview-env.sh new file mode 100644 index 000000000..36ca77f8f --- /dev/null +++ b/scripts/amplify-preview-env.sh @@ -0,0 +1,12 @@ +# Sourced by amplify.yml for PR previews. Amplify gives a preview the app-level environment, not its +# base branch's, and the app level is the legacy production config, so a preview would otherwise sign +# in as remoteit_desktop on login.remote.it. Previews run on dev, matching the main branch's env. +export VITE_OAUTH_ISSUER=https://login.dev.remote.it +export VITE_OAUTH_CLIENT_ID=remoteit_portal +export VITE_OAUTH_GRAPHQL_RESOURCE=https://cloud.dev.remote.it/api +export VITE_OAUTH_AGENT_RESOURCE=https://agent.dev.remote.it +export VITE_OAUTH_MCP_RESOURCE=https://cloud.dev.remote.it/mcp +export VITE_OAUTH_MCP_DETAIL=remoteit_mcp +export VITE_GRAPHQL_API=https://cloud.dev.remote.it/api/graphql +export VITE_WEBSOCKET_URL=wss://cloud.dev.remote.it/api/ws +export VITE_AGENT_URL=https://agent.dev.remote.it From a889474b2f60a49fe6552dcecf477728e49a9a20 Mon Sep 17 00:00:00 2001 From: Jamie Ruderman Date: Wed, 7 Oct 2026 15:55:48 -0700 Subject: [PATCH 2/4] refactor(amplify): previews pin only the dev issuer and derive the rest; leaner reconcile script and 6-hourly backstop --- .github/scripts/preview-callbacks.mjs | 99 ++++++++++++------------- .github/workflows/preview-callbacks.yml | 13 +--- scripts/amplify-preview-env.sh | 12 +-- 3 files changed, 56 insertions(+), 68 deletions(-) diff --git a/.github/scripts/preview-callbacks.mjs b/.github/scripts/preview-callbacks.mjs index ac3f884b0..c1761989b 100644 --- a/.github/scripts/preview-callbacks.mjs +++ b/.github/scripts/preview-callbacks.mjs @@ -2,19 +2,16 @@ // previews. Every other entry belongs to the registry Terraform (authentication // tf-permitteer-registry) and stays in place. import crypto from 'node:crypto' -import { pathToFileURL } from 'node:url' +import { execFileSync } from 'node:child_process' const ISSUER = 'https://login.dev.remote.it' const CLIENT_ID = 'remoteit_portal' const OPERATOR_ID = 'svc_preview_callbacks' -const PREVIEW_HOST = 'd20k671nqqv4kl.amplifyapp.com' // The Amplify branches with pull request previews turned on. const PREVIEW_BASES = ['main', 'release'] +const PREVIEW_URI = /^https:\/\/pr-\d+\.d20k671nqqv4kl\.amplifyapp\.com\/(authCallback|signoutCallback)$/ -const PREVIEW_URI = new RegExp(`^https://pr-\\d+\\.${PREVIEW_HOST.replaceAll('.', '\\.')}/`) -const previewUri = (pull, path) => `https://pr-${pull}.${PREVIEW_HOST}/${path}` - -export async function adminToken(pem, clientId = OPERATOR_ID) { +async function adminToken(pem) { const key = crypto.createPrivateKey(pem) const jwk = crypto.createPublicKey(key).export({ format: 'jwk' }) const kid = crypto @@ -25,8 +22,8 @@ export async function adminToken(pem, clientId = OPERATOR_ID) { const encode = value => Buffer.from(JSON.stringify(value)).toString('base64url') const now = Math.floor(Date.now() / 1000) const signing = `${encode({ alg: 'ES256', kid })}.${encode({ - iss: clientId, - sub: clientId, + iss: OPERATOR_ID, + sub: OPERATOR_ID, aud: ISSUER, iat: now, exp: now + 120, @@ -38,7 +35,7 @@ export async function adminToken(pem, clientId = OPERATOR_ID) { headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ grant_type: 'client_credentials', - client_id: clientId, + client_id: OPERATOR_ID, client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer', client_assertion: `${signing}.${signature.toString('base64url')}`, resource: `${ISSUER}/admin/api`, @@ -49,21 +46,7 @@ export async function adminToken(pem, clientId = OPERATOR_ID) { return body.access_token } -export async function previewPulls(repo, token) { - const pulls = [] - for (let page = 1; ; page++) { - const response = await fetch(`https://api.github.com/repos/${repo}/pulls?state=open&per_page=100&page=${page}`, { - headers: { authorization: `Bearer ${token}`, accept: 'application/vnd.github+json' }, - }) - if (!response.ok) throw new Error(`pulls: ${response.status} ${await response.text()}`) - const batch = await response.json() - // A fork's PR is a stranger's code on a preview URL, so it never gets a callback. - pulls.push(...batch.filter(p => p.head.repo?.full_name === repo && PREVIEW_BASES.includes(p.base.ref))) - if (batch.length < 100) return pulls.map(p => p.number).sort((a, b) => a - b) - } -} - -export async function portal(token, method = 'GET', body) { +async function portal(token, method = 'GET', body) { const response = await fetch(`${ISSUER}/admin/api/clients/${CLIENT_ID}`, { method, headers: { authorization: `Bearer ${token}`, ...(body && { 'content-type': 'application/json' }) }, @@ -73,34 +56,48 @@ export async function portal(token, method = 'GET', body) { return response.json() } -export function desired(client, pulls) { - const withPreviews = (uris = [], path) => [ - ...uris.filter(uri => !PREVIEW_URI.test(uri)), - ...pulls.map(pull => previewUri(pull, path)), - ] - return { - redirectUris: withPreviews(client.redirectUris, 'authCallback'), - postLogoutRedirectUris: withPreviews(client.postLogoutRedirectUris, 'signoutCallback'), - } -} +const open = JSON.parse( + execFileSync( + 'gh', + [ + 'pr', + 'list', + '--repo', + process.env.GITHUB_REPOSITORY, + '--state', + 'open', + '--limit', + '1000', + '--json', + 'number,baseRefName,isCrossRepository', + ], + { encoding: 'utf8' } + ) +) +// A fork's PR is a stranger's code on a preview URL, so it never gets a callback. +const pulls = open + .filter(p => !p.isCrossRepository && PREVIEW_BASES.includes(p.baseRefName)) + .map(p => p.number) + .sort((a, b) => a - b) -export function changes(client, wanted) { - return Object.entries(wanted).flatMap(([field, uris]) => [ - ...uris.filter(uri => !client[field]?.includes(uri)).map(uri => `+ ${field} ${uri}`), - ...(client[field] ?? []).filter(uri => !uris.includes(uri)).map(uri => `- ${field} ${uri}`), - ]) +const token = await adminToken(process.env.PREVIEW_CALLBACKS_KEY) +const client = await portal(token) +const withPreviews = (uris, path) => [ + ...uris.filter(uri => !PREVIEW_URI.test(uri)), + ...pulls.map(pull => `https://pr-${pull}.d20k671nqqv4kl.amplifyapp.com/${path}`), +] +const wanted = { + redirectUris: withPreviews(client.redirectUris, 'authCallback'), + postLogoutRedirectUris: withPreviews(client.postLogoutRedirectUris, 'signoutCallback'), } +const diff = Object.entries(wanted).flatMap(([field, uris]) => [ + ...uris.filter(uri => !client[field].includes(uri)).map(uri => `+ ${field} ${uri}`), + ...client[field].filter(uri => !uris.includes(uri)).map(uri => `- ${field} ${uri}`), +]) -if (import.meta.url === pathToFileURL(process.argv[1]).href) { - const pulls = await previewPulls(process.env.GITHUB_REPOSITORY, process.env.GITHUB_TOKEN) - const token = await adminToken(process.env.PREVIEW_CALLBACKS_KEY) - const client = await portal(token) - const wanted = desired(client, pulls) - const diff = changes(client, wanted) - console.log(`Open previews: ${pulls.map(pull => `#${pull}`).join(' ') || 'none'}`) - if (!diff.length) console.log(`${CLIENT_ID} is up to date.`) - else { - await portal(token, 'PATCH', wanted) - console.log(diff.join('\n')) - } +console.log(`Open previews: ${pulls.map(pull => `#${pull}`).join(' ') || 'none'}`) +if (!diff.length) console.log(`${CLIENT_ID} is up to date.`) +else { + await portal(token, 'PATCH', wanted) + console.log(diff.join('\n')) } diff --git a/.github/workflows/preview-callbacks.yml b/.github/workflows/preview-callbacks.yml index 0d1aa1a23..62a2053d1 100644 --- a/.github/workflows/preview-callbacks.yml +++ b/.github/workflows/preview-callbacks.yml @@ -1,6 +1,4 @@ -# Amplify serves each PR at https://pr-.d20k671nqqv4kl.amplifyapp.com, signed in on dev as -# remoteit_portal, which accepts only exactly registered redirect URIs. This keeps that client's -# preview callbacks equal to the open PRs (authentication tf-permitteer-registry/README.md). +# Registers each open PR's exact Amplify preview callbacks on dev's remoteit_portal (readme.md, Sign-in). name: Preview callbacks on: @@ -8,14 +6,14 @@ on: types: [opened, reopened, closed] branches: [main, release] schedule: - - cron: '23 * * * *' + - cron: '23 */6 * * *' workflow_dispatch: permissions: {} jobs: # The key's environment admits runs on main only, so a PR asks main to reconcile. Dependabot's - # token cannot dispatch; the hourly run picks its PRs up. + # token cannot dispatch; the scheduled run picks its PRs up. request: if: >- github.event_name == 'pull_request' && @@ -40,10 +38,7 @@ jobs: pull-requests: read steps: - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 - with: - node-version-file: .nvmrc - run: node .github/scripts/preview-callbacks.mjs env: - GITHUB_TOKEN: ${{ github.token }} + GH_TOKEN: ${{ github.token }} PREVIEW_CALLBACKS_KEY: ${{ secrets.PREVIEW_CALLBACKS_KEY }} diff --git a/scripts/amplify-preview-env.sh b/scripts/amplify-preview-env.sh index 36ca77f8f..e162e8129 100644 --- a/scripts/amplify-preview-env.sh +++ b/scripts/amplify-preview-env.sh @@ -1,12 +1,8 @@ # Sourced by amplify.yml for PR previews. Amplify gives a preview the app-level environment, not its -# base branch's, and the app level is the legacy production config, so a preview would otherwise sign -# in as remoteit_desktop on login.remote.it. Previews run on dev, matching the main branch's env. +# base branch's, and the app level pins the legacy production API, so a preview would otherwise sign +# in as remoteit_desktop on login.remote.it. Pinning the dev issuer selects STAGES.dev for the rest. +unset VITE_GRAPHQL_API VITE_WEBSOCKET_URL export VITE_OAUTH_ISSUER=https://login.dev.remote.it export VITE_OAUTH_CLIENT_ID=remoteit_portal -export VITE_OAUTH_GRAPHQL_RESOURCE=https://cloud.dev.remote.it/api -export VITE_OAUTH_AGENT_RESOURCE=https://agent.dev.remote.it -export VITE_OAUTH_MCP_RESOURCE=https://cloud.dev.remote.it/mcp -export VITE_OAUTH_MCP_DETAIL=remoteit_mcp -export VITE_GRAPHQL_API=https://cloud.dev.remote.it/api/graphql -export VITE_WEBSOCKET_URL=wss://cloud.dev.remote.it/api/ws +# A pinned build otherwise calls the agent at /agent, which only the vite dev server proxies. export VITE_AGENT_URL=https://agent.dev.remote.it From da85906c1eb33432ab14ef7c4f2b3c8bc34e1b2f Mon Sep 17 00:00:00 2001 From: Jamie Ruderman Date: Wed, 7 Oct 2026 15:58:51 -0700 Subject: [PATCH 3/4] fix(amplify): previews drop every app-level stage pin; reconcile names a missing key and keeps token error status --- .github/scripts/preview-callbacks.mjs | 11 ++++++++--- .github/workflows/preview-callbacks.yml | 1 - scripts/amplify-preview-env.sh | 2 +- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/.github/scripts/preview-callbacks.mjs b/.github/scripts/preview-callbacks.mjs index c1761989b..d885f166d 100644 --- a/.github/scripts/preview-callbacks.mjs +++ b/.github/scripts/preview-callbacks.mjs @@ -41,9 +41,10 @@ async function adminToken(pem) { resource: `${ISSUER}/admin/api`, }), }) - const body = await response.json() - if (!body.access_token) throw new Error(`token: ${response.status} ${JSON.stringify(body)}`) - return body.access_token + const text = await response.text() + const accessToken = response.ok && JSON.parse(text).access_token + if (!accessToken) throw new Error(`token: ${response.status} ${text}`) + return accessToken } async function portal(token, method = 'GET', body) { @@ -80,6 +81,10 @@ const pulls = open .map(p => p.number) .sort((a, b) => a - b) +if (!process.env.PREVIEW_CALLBACKS_KEY) + throw new Error( + 'PREVIEW_CALLBACKS_KEY is not set: run tf-permitteer-registry/preview-callbacks-key.sh in remoteit/authentication' + ) const token = await adminToken(process.env.PREVIEW_CALLBACKS_KEY) const client = await portal(token) const withPreviews = (uris, path) => [ diff --git a/.github/workflows/preview-callbacks.yml b/.github/workflows/preview-callbacks.yml index 62a2053d1..c2cd0261a 100644 --- a/.github/workflows/preview-callbacks.yml +++ b/.github/workflows/preview-callbacks.yml @@ -1,4 +1,3 @@ -# Registers each open PR's exact Amplify preview callbacks on dev's remoteit_portal (readme.md, Sign-in). name: Preview callbacks on: diff --git a/scripts/amplify-preview-env.sh b/scripts/amplify-preview-env.sh index e162e8129..41cf0038a 100644 --- a/scripts/amplify-preview-env.sh +++ b/scripts/amplify-preview-env.sh @@ -1,7 +1,7 @@ # Sourced by amplify.yml for PR previews. Amplify gives a preview the app-level environment, not its # base branch's, and the app level pins the legacy production API, so a preview would otherwise sign # in as remoteit_desktop on login.remote.it. Pinning the dev issuer selects STAGES.dev for the rest. -unset VITE_GRAPHQL_API VITE_WEBSOCKET_URL +unset VITE_GRAPHQL_API VITE_WEBSOCKET_URL VITE_OAUTH_GRAPHQL_RESOURCE VITE_OAUTH_AGENT_RESOURCE VITE_OAUTH_MCP_RESOURCE VITE_OAUTH_MCP_DETAIL export VITE_OAUTH_ISSUER=https://login.dev.remote.it export VITE_OAUTH_CLIENT_ID=remoteit_portal # A pinned build otherwise calls the agent at /agent, which only the vite dev server proxies. From 2a987042aa5190a901164483efaf59379cc88395 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 13 Oct 2026 22:03:29 +0000 Subject: [PATCH 4/4] refactor(amplify): previews build from autodetected repo branches gated by AMPLIFY_PREVIEW; drop the per-PR callback workflow --- .github/scripts/preview-callbacks.mjs | 108 ------------------------ .github/workflows/preview-callbacks.yml | 43 ---------- RELEASE.md | 4 +- amplify.yml | 2 +- readme.md | 11 ++- scripts/amplify-preview-env.sh | 7 +- 6 files changed, 14 insertions(+), 161 deletions(-) delete mode 100644 .github/scripts/preview-callbacks.mjs delete mode 100644 .github/workflows/preview-callbacks.yml diff --git a/.github/scripts/preview-callbacks.mjs b/.github/scripts/preview-callbacks.mjs deleted file mode 100644 index d885f166d..000000000 --- a/.github/scripts/preview-callbacks.mjs +++ /dev/null @@ -1,108 +0,0 @@ -// Keeps remoteit_portal's preview callbacks on the dev login server equal to the open PRs Amplify -// previews. Every other entry belongs to the registry Terraform (authentication -// tf-permitteer-registry) and stays in place. -import crypto from 'node:crypto' -import { execFileSync } from 'node:child_process' - -const ISSUER = 'https://login.dev.remote.it' -const CLIENT_ID = 'remoteit_portal' -const OPERATOR_ID = 'svc_preview_callbacks' -// The Amplify branches with pull request previews turned on. -const PREVIEW_BASES = ['main', 'release'] -const PREVIEW_URI = /^https:\/\/pr-\d+\.d20k671nqqv4kl\.amplifyapp\.com\/(authCallback|signoutCallback)$/ - -async function adminToken(pem) { - const key = crypto.createPrivateKey(pem) - const jwk = crypto.createPublicKey(key).export({ format: 'jwk' }) - const kid = crypto - .createHash('sha256') - .update(JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y })) - .digest('base64url') - .slice(0, 16) - const encode = value => Buffer.from(JSON.stringify(value)).toString('base64url') - const now = Math.floor(Date.now() / 1000) - const signing = `${encode({ alg: 'ES256', kid })}.${encode({ - iss: OPERATOR_ID, - sub: OPERATOR_ID, - aud: ISSUER, - iat: now, - exp: now + 120, - jti: crypto.randomUUID(), - })}` - const signature = crypto.sign('sha256', Buffer.from(signing), { key, dsaEncoding: 'ieee-p1363' }) - const response = await fetch(`${ISSUER}/token`, { - method: 'POST', - headers: { 'content-type': 'application/x-www-form-urlencoded' }, - body: new URLSearchParams({ - grant_type: 'client_credentials', - client_id: OPERATOR_ID, - client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer', - client_assertion: `${signing}.${signature.toString('base64url')}`, - resource: `${ISSUER}/admin/api`, - }), - }) - const text = await response.text() - const accessToken = response.ok && JSON.parse(text).access_token - if (!accessToken) throw new Error(`token: ${response.status} ${text}`) - return accessToken -} - -async function portal(token, method = 'GET', body) { - const response = await fetch(`${ISSUER}/admin/api/clients/${CLIENT_ID}`, { - method, - headers: { authorization: `Bearer ${token}`, ...(body && { 'content-type': 'application/json' }) }, - body: body && JSON.stringify(body), - }) - if (!response.ok) throw new Error(`${method} ${CLIENT_ID}: ${response.status} ${await response.text()}`) - return response.json() -} - -const open = JSON.parse( - execFileSync( - 'gh', - [ - 'pr', - 'list', - '--repo', - process.env.GITHUB_REPOSITORY, - '--state', - 'open', - '--limit', - '1000', - '--json', - 'number,baseRefName,isCrossRepository', - ], - { encoding: 'utf8' } - ) -) -// A fork's PR is a stranger's code on a preview URL, so it never gets a callback. -const pulls = open - .filter(p => !p.isCrossRepository && PREVIEW_BASES.includes(p.baseRefName)) - .map(p => p.number) - .sort((a, b) => a - b) - -if (!process.env.PREVIEW_CALLBACKS_KEY) - throw new Error( - 'PREVIEW_CALLBACKS_KEY is not set: run tf-permitteer-registry/preview-callbacks-key.sh in remoteit/authentication' - ) -const token = await adminToken(process.env.PREVIEW_CALLBACKS_KEY) -const client = await portal(token) -const withPreviews = (uris, path) => [ - ...uris.filter(uri => !PREVIEW_URI.test(uri)), - ...pulls.map(pull => `https://pr-${pull}.d20k671nqqv4kl.amplifyapp.com/${path}`), -] -const wanted = { - redirectUris: withPreviews(client.redirectUris, 'authCallback'), - postLogoutRedirectUris: withPreviews(client.postLogoutRedirectUris, 'signoutCallback'), -} -const diff = Object.entries(wanted).flatMap(([field, uris]) => [ - ...uris.filter(uri => !client[field].includes(uri)).map(uri => `+ ${field} ${uri}`), - ...client[field].filter(uri => !uris.includes(uri)).map(uri => `- ${field} ${uri}`), -]) - -console.log(`Open previews: ${pulls.map(pull => `#${pull}`).join(' ') || 'none'}`) -if (!diff.length) console.log(`${CLIENT_ID} is up to date.`) -else { - await portal(token, 'PATCH', wanted) - console.log(diff.join('\n')) -} diff --git a/.github/workflows/preview-callbacks.yml b/.github/workflows/preview-callbacks.yml deleted file mode 100644 index c2cd0261a..000000000 --- a/.github/workflows/preview-callbacks.yml +++ /dev/null @@ -1,43 +0,0 @@ -name: Preview callbacks - -on: - pull_request: - types: [opened, reopened, closed] - branches: [main, release] - schedule: - - cron: '23 */6 * * *' - workflow_dispatch: - -permissions: {} - -jobs: - # The key's environment admits runs on main only, so a PR asks main to reconcile. Dependabot's - # token cannot dispatch; the scheduled run picks its PRs up. - request: - if: >- - github.event_name == 'pull_request' && - github.event.pull_request.head.repo.full_name == github.repository && - github.actor != 'dependabot[bot]' - runs-on: ubuntu-latest - permissions: - actions: write - steps: - - run: gh workflow run preview-callbacks.yml --repo "$GITHUB_REPOSITORY" --ref main - env: - GH_TOKEN: ${{ github.token }} - - reconcile: - if: github.event_name != 'pull_request' - runs-on: ubuntu-latest - environment: preview-callbacks - concurrency: - group: preview-callbacks - permissions: - contents: read - pull-requests: read - steps: - - uses: actions/checkout@v4 - - run: node .github/scripts/preview-callbacks.mjs - env: - GH_TOKEN: ${{ github.token }} - PREVIEW_CALLBACKS_KEY: ${{ secrets.PREVIEW_CALLBACKS_KEY }} diff --git a/RELEASE.md b/RELEASE.md index 24c8451cb..9d5a60963 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -220,8 +220,8 @@ Empty means it is safe to fast-forward and something else is wrong (branch protection, most likely). Not empty means there is work on `release` to merge back into `main` first. -Amplify builds the branch. Its build settings live in the Amplify console, not -in this repo, so there is no `amplify.yml` here to change. +Amplify builds the branch from `amplify.yml` in this repo. A branch that +contains it ignores the build settings in the Amplify console. ## Windows installer payloads diff --git a/amplify.yml b/amplify.yml index 9162b57b1..abd3c30c7 100644 --- a/amplify.yml +++ b/amplify.yml @@ -8,7 +8,7 @@ frontend: - npm install build: commands: - - if [ -n "$AWS_PULL_REQUEST_ID" ]; then . ./scripts/amplify-preview-env.sh; fi; npm run build-frontend + - if [ "$AMPLIFY_PREVIEW" = true ]; then . ./scripts/amplify-preview-env.sh; fi; npm run build-frontend artifacts: baseDirectory: frontend/build files: diff --git a/readme.md b/readme.md index 128b8321a..724594a41 100644 --- a/readme.md +++ b/readme.md @@ -122,10 +122,13 @@ Leave `VITE_OAUTH_CLIENT_ID` as `remoteit_desktop` locally. Redirect URIs are re branch config makes authorize fail with a 400. `remoteit_desktop` carries both `http://localhost:3003/authCallback` and `remoteit://authCallback` (the Electron deep link). -PR previews (`https://pr-.d20k671nqqv4kl.amplifyapp.com`) build on the dev stage as -`remoteit_portal` (`amplify.yml` sources `scripts/amplify-preview-env.sh`). The Preview callbacks -workflow registers each open PR's exact callbacks and removes them when it closes. A PR from a fork -gets none, so its preview cannot sign in. +Branch previews build on the dev stage as `remoteit_portal`. Amplify autodetects `feat/**` and +`fix/**` branches pushed to this repo, deploys each to its own `*.d20k671nqqv4kl.amplifyapp.com` +address and drops it when the branch is deleted. Its auto-created branch config sets +`AMPLIFY_PREVIEW=true`, which makes `amplify.yml` source `scripts/amplify-preview-env.sh`. Sign-in +needs `https://*.d20k671nqqv4kl.amplifyapp.com/authCallback` and `/signoutCallback` registered on +dev's `remoteit_portal`. That wildcard is safe only while nothing from outside this repo can deploy +under the app's domain, so keep Amplify's **pull request previews off**: they build PRs from forks. Browse to `http://localhost:3003` exactly. `npm start` binds `0.0.0.0`, but reaching the app over a LAN IP is a non-secure origin, where `crypto.subtle` is unavailable and the DPoP diff --git a/scripts/amplify-preview-env.sh b/scripts/amplify-preview-env.sh index 41cf0038a..f9711e991 100644 --- a/scripts/amplify-preview-env.sh +++ b/scripts/amplify-preview-env.sh @@ -1,6 +1,7 @@ -# Sourced by amplify.yml for PR previews. Amplify gives a preview the app-level environment, not its -# base branch's, and the app level pins the legacy production API, so a preview would otherwise sign -# in as remoteit_desktop on login.remote.it. Pinning the dev issuer selects STAGES.dev for the rest. +# Sourced by amplify.yml for branch previews: the branches Amplify autodetects, whose auto-created +# branch config sets AMPLIFY_PREVIEW=true. A preview also gets the app-level environment, and the app +# level pins the legacy production API, so a preview would otherwise sign in as remoteit_desktop on +# login.remote.it. Pinning the dev issuer selects STAGES.dev for the rest. unset VITE_GRAPHQL_API VITE_WEBSOCKET_URL VITE_OAUTH_GRAPHQL_RESOURCE VITE_OAUTH_AGENT_RESOURCE VITE_OAUTH_MCP_RESOURCE VITE_OAUTH_MCP_DETAIL export VITE_OAUTH_ISSUER=https://login.dev.remote.it export VITE_OAUTH_CLIENT_ID=remoteit_portal