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
Original file line number Diff line number Diff line change
@@ -1 +1 @@
64a6d708f5a43f2cd3fde5d4d7db3905ba1bdf65
2b4aa13a72dd47cd135b06ce5abfccd92e19b24f
4 changes: 2 additions & 2 deletions skills/modern-web-guidance/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ Run `modern-web-guidance` directly with `npx` using a **2–5 word action-orient
- **Example**: Search `"light dismiss dialog"` or `"responsive data table"`, **not** `"dialog"` (too terse), `"responsive table dark mode"` (compound — split into two searches), or `"close React settings modal on outside click"` (framework/app noise).

```sh
npx -y modern-web-guidance@latest search "<query>" --skill-version 2026_11_10-47b4c80e
npx -y modern-web-guidance@latest search "<query>" --skill-version 2026_11_16-268fb9ea
```

> **Note**: Returns `[{ "id", "description" }, ...]`. Judge results by their `description` fields:
Expand All @@ -30,7 +30,7 @@ npx -y modern-web-guidance@latest search "<query>" --skill-version 2026_11_10-47

### Step 2. Retrieve Best Practices

Once you have relevant `id`(s) from the search results, call `retrieve` to get the full guide(s)—including both specific use-case guides that match your task and any broader discipline guide (e.g., `html`, `css`, `forms`, `accessibility`, `color`, `performance`, `security`) that applies. You can pass multiple IDs separated by commas.
Once you have relevant `id`(s) from the search results, call `retrieve` to get the full guide(s)—including both specific use-case guides that match your task and any broader discipline guide (e.g., `html`, `css`, `js`, `forms`, `accessibility`, `color`, `performance`, `security`) that applies. You can pass multiple IDs separated by commas.

```sh
npx -y modern-web-guidance@latest retrieve "<id>"
Expand Down
2 changes: 1 addition & 1 deletion skills/modern-web-guidance/guides/css/css-layout.md
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ Supported by: Chrome 108 (Nov 2022), Edge 108 (Dec 2022), Firefox 101 (May 2022)
## 8 Grid lanes (aka masonry)

Browser support for Grid lanes: Limited availability.
Supported by: Safari 27.2.
Supported by: Safari 27.2 (Oct 2026).
Unsupported in: Chrome, Edge, and Firefox.

The specification is in development under the name "grid lanes" (e.g., `display: grid-lanes`), while earlier experimental prototypes used `grid-template-rows: masonry`.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ input[type="range"]::-webkit-slider-runnable-track {

2. **Add JavaScript**: Update the variable on the `input` event:
```javascript
if (!CSS.supports('accent-color')) {
if (!CSS.supports('accent-color', 'auto')) {
const slider = document.getElementById('volume');
slider.addEventListener('input', (e) => {
e.target.style.setProperty('--progress', `${e.target.value}%`);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ By utilizing top-level await, you can encapsulate the conditional loading logic

### Conditional polyfill pattern

While top-level `await` can be used to conditionally load any async dependency that's a module, a good use of the conditional depenency loading pattern is to conditionally load polyfills for browsers that don't support a specific feature. This approach encapsulates feature detection and the dynamic import inside a single dependency module.
While top-level `await` can be used to conditionally load any async dependency that's a module, a good use of the conditional dependency loading pattern is to conditionally load polyfills for browsers that don't support a specific feature. This approach encapsulates feature detection and the dynamic import inside a single dependency module.

In the following case, the `popover` attribute polyfill is conditionally loaded if it isn't present on `HTMLElement.prototype`:

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,19 +46,24 @@ Use the `autofocus` attribute on dedicated sign-in pages and sign-in dialogs so

Use the `aria-describedby` attribute on elements with `autofocus` so instructions and context are provided for screen reader users.

Give every input a visible `<label>` associated through `for` and `id`. `aria-describedby` only adds a description; it does not name the field.

```html
<h1 id="signin-passkey">Sign In with Passkey</h1>
<!-- Autocomplete tokens must contain webauthn space-separated -->
<form id="signin-form">
<label for="username">Username</label>
<input
type="text"
id="username"
name="username"
aria-describedby="signin-passkey"
autocomplete="username webauthn"
autofocus
data-testid="username-field"
/>
<input type="password" name="password" autocomplete="current-password" />
<label for="password">Password</label>
<input type="password" id="password" name="password" autocomplete="current-password" />
<button type="submit">Sign in</button>
</form>
```
Expand Down
49 changes: 44 additions & 5 deletions skills/modern-web-guidance/guides/security/security.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ Guidelines for implementing preventative security measures on the web safely and
- 1.3 Secure Cookies
- 1.4 Clickjacking Protection (Frame-Ancestors & X-Frame-Options)
- 1.5 Secure Window Messaging (postMessage)
- 1.6 Secure WebSocket Connections
- Phase 2: Discovery & Data Collection (Prerequisites)
- 2.1 Inspect the Application
- 2.2 Deploy Report-Only Policies
Expand Down Expand Up @@ -127,6 +128,39 @@ window.addEventListener('message', (event) => {
targetWindow.postMessage({ action: 'update' }, 'https://trusted-origin.com');
```

### 1.6 Secure WebSocket Connections
Browsers do **not** enforce CORS on WebSocket handshakes and still attach eligible cookies to upgrade requests (including `SameSite=Lax` and `SameSite=Strict` cookies from same-site subdomains or ports, `SameSite=None` cookies cross-site, and unattributed cookies in browsers without `Lax`-by-default), so WebSocket endpoints require explicit server-side `Origin` validation to prevent Cross-Site WebSocket Hijacking (CSWSH).
- **DO**: Use `wss://` (TLS) for non-local public WebSocket endpoints. Although `https://` Mixed Content blocks public `ws://` connections, `http://` pages and hardcoded `ws://` configurations remain vulnerable; reserve `ws://` for loopback development or explicit Local Network Access exemptions (private IP literals and `.local` mDNS hostnames; see `local-network-access` (via `npx -y modern-web-guidance@latest retrieve "local-network-access"`)).
- **DO**: Strictly validate the `Origin` header against an explicit allowlist of trusted origins inside the WebSocket handshake handler (for example, an HTTP/1.1 `upgrade` or HTTP/2 Extended `CONNECT` handler), rejecting missing or unexpected origins with HTTP `403` before completing the handshake.
- **DO NOT**: Rely on `Sec-Fetch-*` headers instead of `Origin` on WebSocket handshakes — not all browsers send `Sec-Fetch-*` on WebSocket upgrades (so rejecting missing headers breaks connections, while allowing missing headers leaves those browsers unprotected), and `Sec-Fetch-Site: same-site` still permits untrusted subdomains.
- **DO NOT**: Pass authentication tokens or secrets in WebSocket URL query parameters (`wss://example.com/ws?token=...`) or `Sec-WebSocket-Protocol` headers — both leak credentials into server access logs and proxies.
- **DO**: Authenticate WebSocket sessions by pairing strict server-side `Origin` validation with hardened session cookies (§1.3 — note that `__Host-` cookies are host-only and will not be sent to a separate WebSocket subdomain, which requires `__Secure-` with `Domain` or non-cookie auth), or by requiring authentication in the first WebSocket message over `wss://` (closing the socket after a short timeout if unauthenticated).

```javascript
import { WebSocketServer } from 'ws';

// Replace with your application's trusted origin(s)
const ALLOWED_ORIGINS = new Set(['https://app.example.com']);
// Use noServer so `ws` does not register a competing `upgrade` listener that bypasses checks.
const wss = new WebSocketServer({ noServer: true });

server.on('upgrade', (req, socket, head) => {
// Node drops its default socket error handler on `upgrade`; prevent unhandled ECONNRESET crashes.
socket.on('error', () => {});

const origin = req.headers.origin;
if (!origin || !ALLOWED_ORIGINS.has(origin)) {
socket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\nContent-Length: 0\r\n\r\n');
return;
}

// Verify the hardened session cookie (§1.3) or enforce first-message auth with a short timeout.
wss.handleUpgrade(req, socket, head, (ws) => {
wss.emit('connection', ws, req);
});
});
```

## Phase 2: Discovery & Data Collection (Prerequisites)

Do not blindly apply strict policies to an existing application. You must first understand the application's constraints by collecting data.
Expand Down Expand Up @@ -293,15 +327,20 @@ Set CORP explicitly on each response based on whether it should be embeddable in

Highest deployment breakage risk. You only need to deploy this infrastructure if the application requires features relying on `SharedArrayBuffer` (e.g., WebAssembly multi-threading or shared memory architectures). If not required, skip this policy group.

- **Preferred path (Chromium environments)**: Enable `Document-Isolation-Policy: isolate-and-credentialless`. This provides client-side isolation comparable to COEP while instructing the browser to strip cookies and authentication credentials from non-CORS cross-origin resource fetches rather than blocking them outright. Note that this is supported primarily in Chrome (142+) and other vendors have not yet shown interest, so evaluate carefully based on your target audience. Apps that need to *block* cross-origin resources lacking explicit CORP opt-in (rather than load them with credentials stripped) can adopt `isolate-and-require-corp` instead. This is stricter and harder to deploy — it requires the same subresource audit as the cross-browser path below.
- **Cross-browser path (Complex enforcement)**: Require `Cross-Origin-Opener-Policy: same-origin` coupled with `Cross-Origin-Embedder-Policy: require-corp`. Every embedded subresource (images, styles, external media) MUST serve an explicit `Cross-Origin-Resource-Policy` header or the browser will prevent it from loading.
- **DO (Cross-browser default — COOP + COEP)**: Serve the document with `Cross-Origin-Opener-Policy: same-origin` coupled with `Cross-Origin-Embedder-Policy: require-corp` (or `Cross-Origin-Embedder-Policy: credentialless` where supported). Under `require-corp`, every cross-origin subresource (images, scripts, styles, media) MUST explicitly opt in via either a `Cross-Origin-Resource-Policy` header (`cross-origin` or `same-site`) or CORS (`crossorigin` attribute paired with `Access-Control-Allow-Origin`), and any embedded cross-origin `<iframe>` must both send `Cross-Origin-Resource-Policy` (`cross-origin` or `same-site`) and enforce COEP, or the browser will block it.

```http
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp
Cross-Origin-Resource-Policy: same-origin
```

Browser support for Document-Isolation-Policy: Limited availability.
Supported by: Chrome 137 (May 2025) and Edge 137 (May 2025).
Unsupported in: Firefox and Safari.

- **DO (Alternative where supported — Document-Isolation-Policy)**: Where supported, you can serve `Document-Isolation-Policy: isolate-and-credentialless` on the document requiring `SharedArrayBuffer` to isolate at the document level without severing cross-origin `window.opener` popup references or requiring embedded third-party iframes to deploy COEP, while stripping cookies and credentials from non-CORS cross-origin subresource requests. Use `Document-Isolation-Policy: isolate-and-require-corp` instead if you need to block cross-origin subresources lacking explicit CORP or CORS opt-in.

#### 3.7 Fetch Metadata (Resource Isolation)
Server-side enforcement that uses `Sec-Fetch-*` request headers to reject suspicious cross-site requests. Requires the cross-site integration mapping from §2.1 before enforcing.

Expand All @@ -310,6 +349,7 @@ Server-side enforcement that uses `Sec-Fetch-*` request headers to reject suspic
- **DO**: Include `Vary: Sec-Fetch-Dest, Sec-Fetch-Mode, Sec-Fetch-Site` to prevent intermediate caches (CDNs) from serving cached responses to attackers.
- **CAUTION**: `same-site` trusts every subdomain under your eTLD+1. If any subdomain hosts user-generated content, a legacy app, or otherwise untrusted code, drop `same-site` from the allowlist and accept only `same-origin` and `none`.
- **CAUTION**: Misconfiguring these checks will block legitimate API requests coming from cross-site integrations, SSO handlers, or Webhooks. Ensure you log and test your `Sec-Fetch-*` constraints beforehand.
- **CAUTION**: Fetch Metadata middleware does not cover WebSocket handshakes; validate `Origin` in your WebSocket handshake handler (see §1.6).

```javascript
app.use((req, res, next) => {
Expand Down Expand Up @@ -349,16 +389,15 @@ These carry significantly lower breakage risk than the core enforcement track. T

#### Permissions Policy
- **DO**: Disable unused browser features (camera, geolocation, microphone) for the page and iframes using Structured Fields syntax.
- **DO**: Disable `focus-without-user-activation` for third-party iframes to prevent focus stealing.
- **DO**: When delegating features to an iframe, use the `allow` attribute in HTML *in addition* to the header.
- **CAUTION**: Unintentionally blocking a delegated feature will cause silent failures in third-party widgets (like embedded video players or payment gateways). Audit third-party dependencies before blocking.

```http
Permissions-Policy: camera=(), geolocation=(), microphone=(), focus-without-user-activation=()
Permissions-Policy: camera=(), geolocation=(), microphone=()
```

```html
<iframe src="https://trusted-video.com/player" allow="fullscreen; camera; focus-without-user-activation 'none'"></iframe>
<iframe src="https://trusted-video.com/player" allow="fullscreen"></iframe>
```

#### Subresource Integrity (SRI)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -170,4 +170,14 @@ Caveats when using the polyfill:
}
```

To prevent popovers from showing before the polyfill loads, hide them with CSS:

```css
@supports not selector(:popover-open) {
[popover]:not(.\:popover-open) {
display: none;
}
}
```

Browsers without support for the Popover API also do not support anchor positioning, so the tooltip will appear in the center of the screen.
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,16 @@ Caveats when using the polyfill:
}
```

To prevent popovers from showing before the polyfill loads, hide them with CSS:

```css
@supports not selector(:popover-open) {
[popover]:not(.\:popover-open) {
display: none;
}
}
```

### Fallbacks & browser support for Anchor positioning

Browser support for Anchor positioning: Limited availability.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,15 @@ ul::before {
}
```

Position the underline relative to the anchor using the inset properties and `anchor()` functions.
Position the underline with logical insets and `anchor(self-start)` or `anchor(self-end)`. Unlike `start` and `end`, these keywords use the underline's own writing mode rather than its containing block's. This keeps the anchor sides consistent with the logical insets when an RTL tab list is inside an LTR page and no ancestor of the underline establishes a containing block within the RTL section.

```css
ul::before {
/* DO NOT use position-area, which can not be transitioned. */
/* Use calc() to offset the top slightly */
inset-block-start: calc(anchor(bottom) + .1lh);
inset-inline-start: anchor(left);
inset-inline-end: anchor(right);
/* Add a small gap between the indicator and the tab's block-end edge. */
inset-block-start: calc(anchor(self-end) + .1lh);
inset-inline-start: anchor(self-start);
inset-inline-end: anchor(self-end);
}
```

Expand Down Expand Up @@ -82,17 +82,30 @@ This is only a visual indicator, and must not be a replacement for setting the a

## Fallback strategies

Browser support for Anchor positioning: Limited availability.
Supported by: Chrome 157 (Nov 2026), Edge 157 (Nov 2026), and Safari 27 (Sep 2026).
Unsupported in: Firefox.
### Anchor positioning

Baseline status for the css.types.anchor capability: Newly available. It's been Baseline since 2026-01-13.
Supported by: Chrome 125 (May 2024), Edge 125 (May 2024), Firefox 147 (Jan 2026), and Safari 26 (Sep 2025).

If anchor positioning is not supported in the browser, use a `border-bottom` to add an underline. It will not be animated.
If the browser lacks the anchor positioning used here, hide the pseudo-element and draw a static `border-block-end` on the active tab. The border follows the tab's writing mode.

```css
ul li.active {
@supports not (position-anchor: auto) {
@supports not (position-anchor: --active) {
ul::before {
content: none;
}

ul li.active {
/* Choose a color appropriate to the app theme. */
border-bottom: .25lh var(--primary) solid;
border-block-end: .25lh solid currentColor;
}
}
```
```

### Anchor positioning animations

Browser support for Anchor positioning animations and transitions: Limited availability.
Supported by: Chrome 125 (May 2024), Edge 125 (May 2024), and Safari 26 (Sep 2025).
Unsupported in: Firefox.

If the browser can position the underline but cannot transition `anchor()` values, keep the anchored underline. It moves directly to the new active tab when selection changes.
Original file line number Diff line number Diff line change
Expand Up @@ -240,3 +240,13 @@ Caveats when using the polyfill:
display: block;
}
```

To prevent popovers from showing before the polyfill loads, hide them with CSS:

```css
@supports not selector(:popover-open) {
[popover]:not(.\:popover-open) {
display: none;
}
}
```
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ const commandRegistry = {
## Key constraints

* **Prefix custom commands**: MANDATORY: All custom command names must start with `--` (e.g., `command="--my-action"`).
* **Targeting**: The `commandfor` attribute must match the `id` of an element in the same document tree.
* **Targeting**: The `commandfor` attribute must match the `id` of an element in the same tree as the button (the same document or shadow root).
* **No bubbling**: The `command` event does not bubble. If there multiple possible targets, add `{ capture: true }` to the event handler and listen on an ancestor.
* **Shadow roots**: If the target may be in a shadow root, use `event.composedPath()[0]` instead of `event.target`.
* **Accessibility**: Custom commands have no inherent semantics, and you must explicitly apply any states.
Expand Down Expand Up @@ -158,10 +158,13 @@ if (!globalThis.CommandEvent) {

// 3. The fallback: Dispatch events manually if native support is missing
document.addEventListener('click', (event) => {
// Respect handlers that already canceled the button's activation.
if (event.defaultPrevented) return;
const button = event.composedPath().find((el) => el.matches?.("button[commandfor]"));
if (!button) return;

const target = document.getElementById(button.getAttribute('commandfor'));
// Resolve within the button's tree, since IDs can repeat across shadow roots.
const target = button.getRootNode().getElementById(button.getAttribute('commandfor'));
const command = button.getAttribute('command');

if (target && command) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,3 +151,13 @@ Caveats when using the polyfill:
display: block;
}
```

To prevent popovers from showing before the polyfill loads, hide them with CSS:

```css
@supports not selector(:popover-open) {
[popover]:not(.\:popover-open) {
display: none;
}
}
```
Loading