Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
215 changes: 215 additions & 0 deletions public/stack-releases.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
/**
* Same-origin fetch of GET /api/releases for the Stack page.
* State thresholds mirror worker/src/release-display.ts.
*/

const RELEASE_STALE_AFTER_MS = 12 * 60 * 60 * 1000;
const SAFE_REPO = /^[A-Za-z0-9_.-]+$/;
const SAFE_TAG = /^[A-Za-z0-9._+/~^-]+$/;
const GITHUB_ORG_PREFIX = 'https://github.com/pegma-dev/';

const statusNode = document.querySelector('#release-status');
const releaseLines = document.querySelectorAll('.release-line[data-repository]');

function classifyReleaseState(current, nowMs, fetchFailed) {
if (fetchFailed) {
return 'unavailable';
}
if (current === null || current === undefined) {
return 'empty';
}
const observedMs = Date.parse(current.observedAt);
if (
Number.isFinite(observedMs) &&
nowMs - observedMs > RELEASE_STALE_AFTER_MS
) {
return 'stale';
}
return 'populated';
}

function formatReleaseLabel(current) {
const publishedMs = Date.parse(current.publishedAt);
if (!Number.isFinite(publishedMs)) {
return current.tagName;
}
const published = new Date(publishedMs).toISOString().slice(0, 10);
return `${current.tagName} · ${published}`;
}

function isSafeCurrent(current, repositoryName) {
if (
current === null ||
typeof current !== 'object' ||
typeof current.tagName !== 'string' ||
typeof current.releaseUrl !== 'string' ||
typeof current.publishedAt !== 'string' ||
typeof current.observedAt !== 'string'
) {
return false;
}
if (!SAFE_REPO.test(repositoryName) || !SAFE_TAG.test(current.tagName)) {
return false;
}
const expected = `${GITHUB_ORG_PREFIX}${repositoryName}/releases/tag/${current.tagName}`;
return current.releaseUrl === expected;
}

function setStatus(state, message) {
if (!(statusNode instanceof HTMLElement)) {
return;
}
statusNode.dataset.state = state;
statusNode.textContent = message;
}

function setLineState(line, state, content) {
const value = line.querySelector('.release-value');
if (!(value instanceof HTMLElement)) {
return;
}
value.dataset.state = state;
value.replaceChildren();
if (typeof content === 'string') {
value.textContent = content;
return;
}
value.append(content);
}

function renderPopulated(line, current) {
const link = document.createElement('a');
link.href = current.releaseUrl;
link.textContent = formatReleaseLabel(current);
link.rel = 'noopener noreferrer';
setLineState(line, 'populated', link);
}

function renderStale(line, current) {
const wrap = document.createDocumentFragment();
const link = document.createElement('a');
link.href = current.releaseUrl;
link.textContent = formatReleaseLabel(current);
link.rel = 'noopener noreferrer';
wrap.append(link);
wrap.append(document.createTextNode(' (may be stale)'));
setLineState(line, 'stale', wrap);
}

function applyReleases(body, fetchFailed) {
const nowMs = Date.now();
const byName = new Map();
if (
body !== null &&
typeof body === 'object' &&
Array.isArray(body.releases)
) {
for (const entry of body.releases) {
if (
entry !== null &&
typeof entry === 'object' &&
typeof entry.repositoryName === 'string'
) {
byName.set(entry.repositoryName, entry);
}
}
}

let populated = 0;
let stale = 0;

for (const line of releaseLines) {
if (!(line instanceof HTMLElement)) {
continue;
}
const repositoryName = line.dataset.repository ?? '';
const entry = byName.get(repositoryName);
const rawCurrent = entry?.current ?? null;
const current =
rawCurrent !== null && isSafeCurrent(rawCurrent, repositoryName)
? rawCurrent
: null;
const state = classifyReleaseState(current, nowMs, fetchFailed);

if (state === 'unavailable') {
setLineState(line, 'unavailable', 'Temporarily unavailable');
continue;
}
if (state === 'empty' || current === null) {
setLineState(line, 'empty', 'No stable release recorded yet');
continue;
}
if (state === 'stale') {
stale += 1;
renderStale(line, current);
continue;
}
populated += 1;
renderPopulated(line, current);
}

if (fetchFailed) {
setStatus(
'unavailable',
'Current release versions are temporarily unavailable. Repository links below still work.',
);
return;
}

if (populated === 0 && stale === 0) {
setStatus(
'empty',
'No stable release versions are recorded yet. Repository links below still work.',
);
return;
}

if (stale > 0 && populated === 0) {
setStatus(
'stale',
'Release versions are available but may be stale. Repository links remain authoritative.',
);
return;
}

if (stale > 0) {
setStatus(
'stale',
`Showing current stable releases (${stale} may be stale). Values come from D1, not a site rebuild.`,
);
return;
}

setStatus(
'populated',
'Showing current stable releases from the live API (no site rebuild required).',
);
Comment thread
FlyOverCoderKY marked this conversation as resolved.
Resolved
}

async function start() {
try {
const response = await fetch('/api/releases', {
credentials: 'same-origin',
headers: { Accept: 'application/json' },
});
if (!response.ok) {
applyReleases(null, true);
return;
}
const body = await response.json();
if (
body === null ||
typeof body !== 'object' ||
body.schema !== 'pegma.releases.v1' ||
!Array.isArray(body.releases)
) {
applyReleases(null, true);
return;
}
applyReleases(body, false);
} catch {
applyReleases(null, true);
}
}

await start();
24 changes: 24 additions & 0 deletions src/pages/stack.astro
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,15 @@ const withStage = await Promise.all(components.map(compileComponentStatus));
<code>docs/PROJECT_PLAN.md</code> where one exists; the rest fall back to a snapshot dated
{SNAPSHOT_DATE}. The repos are the source of truth.
</p>
<p
id="release-status"
class="notice release-status"
role="status"
aria-live="polite"
data-state="loading"
>
Loading current stable release versions…
</p>
</section>

{
Expand Down Expand Up @@ -52,6 +61,12 @@ const withStage = await Promise.all(components.map(compileComponentStatus));
</ul>
</div>
</div>
<p class="release-line" data-repository={c.repo}>
<strong>Release:</strong>{' '}
<span class="release-value" data-state="loading">
Loading…
</span>
</p>
<p class="now-line">
<strong>Now:</strong> {c.stage ?? c.now} —{' '}
<a href={`https://github.com/pegma-dev/${c.repo}`}>repository</a>
Expand All @@ -65,4 +80,13 @@ const withStage = await Promise.all(components.map(compileComponentStatus));
</section>
))
}

<noscript>
<p class="notice">
Current release versions load from a same-origin API when JavaScript is available. Repository
links above remain the durable path to each component.
</p>
</noscript>

<script is:inline type="module" src="/stack-releases.js"></script>
</Base>
33 changes: 33 additions & 0 deletions src/styles/global.css
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,39 @@ h2 {
color: var(--slate);
}

.release-status {
margin-top: 1rem;
}

.release-status[data-state="unavailable"] {
border-left-color: #a33;
}

.release-line {
margin: 1rem 0 0;
font-size: 0.95rem;
color: var(--slate);
}

.release-value[data-state="loading"] {
font-style: italic;
}

.release-value[data-state="empty"],
.release-value[data-state="unavailable"] {
color: var(--slate);
}

.release-value[data-state="stale"] {
color: var(--slate);
}

.release-value[data-state="populated"] a,
.release-value[data-state="stale"] a {
font-weight: 650;
color: var(--ink);
}

/* First-party account reference surface */
.account-hero {
padding: 3.5rem 0 1.5rem;
Expand Down
5 changes: 5 additions & 0 deletions worker/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,11 @@ public acknowledgement endpoint.
- `POST /api/identity/email-code/sign-in/options|verify` — enumeration-safe
fallback sign-in.
- `POST /api/identity/logout` — server-side revocation and cookie expiry.
- `GET /api/releases` — public current-stable release summaries for allowlisted
Pegma repositories, in component-registry order. JSON schema
`pegma.releases.v1`; short public cache (`max-age=300`) and `ETag`; no
receipt, delivery, or payload fields. Empty `current` when no stable release
is recorded. The Stack page loads this same-origin endpoint at runtime.
- `POST /api/webhooks/github/releases` — authenticated GitHub organization
release webhook. Requires managed secret `GITHUB_WEBHOOK_SECRET` plus vars
`GITHUB_ORGANIZATION_ID` and `GITHUB_ALLOWED_REPOSITORY_IDS`. Invalid traffic
Expand Down
42 changes: 42 additions & 0 deletions worker/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
readGitHubReleaseWebhookConfig,
type GitHubReleaseWebhookEnv,
} from './github-release-webhook';
import { handleGetReleases, readReleasesConfig } from './releases-api';

type AppEnv = Env & LoggerEnv & IdentityRuntimeEnv & GitHubReleaseWebhookEnv;

Expand Down Expand Up @@ -71,6 +72,47 @@ export default {
return Response.json(body, { status });
}

if (path === '/api/releases') {
const releasesConfig = readReleasesConfig(env);
if (releasesConfig === null) {
logger.log('error', 'releases_api.not_configured', {});
return Response.json(
{ error: 'releases_not_configured' },
{
status: 503,
headers: {
'Cache-Control': 'no-store',
'Content-Type': 'application/json; charset=utf-8',
'X-Content-Type-Options': 'nosniff',
},
},
);
}
try {
return await handleGetReleases({
request,
store: createProductionStore(env),
logger,
config: releasesConfig,
});
} catch (error) {
logger.log('error', 'releases_api.unavailable', {
error: error instanceof Error ? error.name : 'unknown',
});
return Response.json(
{ error: 'releases_unavailable' },
{
status: 503,
headers: {
'Cache-Control': 'no-store',
'Content-Type': 'application/json; charset=utf-8',
'X-Content-Type-Options': 'nosniff',
},
},
);
}
}

if (path === '/api/webhooks/github/releases') {
const config = readGitHubReleaseWebhookConfig(env);
if (config === null) {
Expand Down
Loading