1
---
2
name: dpop-adoption
3
metadata:
4
version: "1.0.1"
5
category: Identity
6
description: >-
7
Implement and debug OAuth 2.0 DPoP (RFC 9449) refresh token sender-constraining
8
for WebCrypto, Node.js ES6, and browser runtimes integrating with Google's OAuth
9
platform. Use when configuring non-extractable asymmetric key pairs (P-256),
10
generating DPoP Proof JWTs for authorization code exchange and token refresh, or
11
handling 400 use_dpop_nonce challenge retry loops at oauth2.googleapis.com/token.
12
Don't use for unconstrained OAuth 2.0 flows (where refresh tokens are not bound
13
to a client key pair), or for Google Cloud IAM / service account authentication.
14
---
15
16
# DPoP Adoption & Identity Security Architecture
17
18
Demonstrating Proof-of-Possession (DPoP, RFC 9449) secures OAuth 2.0 refresh
19
tokens against interception and replay attacks by cryptographically binding them
20
to a private key held exclusively by the client. In Google's OAuth 2.0 platform,
21
DPoP binds the refresh token at the token endpoint, while access tokens issued
22
for Google APIs are standard Bearer tokens (`token_type: "Bearer"`).
23
24
## 1. Core Cryptographic & Architectural Invariants
25
26
When implementing DPoP helpers or upgrading HTTP clients, you MUST adhere to the
27
following strict security invariants:
28
29
### A. Universal WebCrypto & Runtime Compatibility
30
31
- In modern ES6 JavaScript (`"type": "module"` for Node 18+ and browsers),
32
ALWAYS access `globalThis.crypto` directly after verifying the environment
33
context.
34
- **NEVER** import legacy CommonJS modules via `require('node:crypto')` or
35
reference browser-scoped `window.crypto`, as these cause module
36
initialization crashes across hybrid runtimes.
37
38
### B. Hardware-Backed Non-Extractable Key Persistence
39
40
- Generate an Elliptic Curve key pair on the SECP256R1 (`P-256`) curve: `{
41
name: 'ECDSA', namedCurve: 'P-256' }`.
42
- **CRITICAL SECURITY GUARDRAIL:** The private key MUST be configured as
43
**non-extractable** (`extractable: false`). This guarantees the private key
44
can never leave the platform's cryptographic boundary (Secure Enclave,
45
Android KeyStore, or JS sandbox memory), thwarting XSS and dependency token
46
theft attacks.
47
- **Runtime Persistence Scope:** In-memory WebCrypto (`extractable: false`)
48
key generation applies to browser/IndexedDB contexts and single-process
49
runtime harnesses; multi-instance or persistent server-side Node.js
50
deployments should bind DPoP private keys via KMS/HSM/TPM so bound refresh
51
tokens survive process restarts.
52
- The public key MUST remain exportable (`extractable: true`) to allow
53
emitting JSON Web Keys (JWKs).
54
55
### C. Public JWK Formatting Standards
56
57
- When exporting public keys to attach to DPoP Proof JWT headers, construct a
58
clean JWK dictionary containing strictly:
59
- `"kty": "EC"`
60
- `"crv": "P-256"`
61
- `"x"`: Base64URL-encoded x-coordinate without trailing equal sign
62
padding (`=`).
63
- `"y"`: Base64URL-encoded y-coordinate without trailing equal sign
64
padding (`=`).
65
- **NEVER** expose private key parameters (`"d"`) or superfluous metadata.
66
67
### D. IEEE P1363 vs. ASN.1 DER Signature Disambiguation
68
69
- DPoP Proof JWTs require raw concatenated coordinate signatures ($R \parallel
70
S$, exactly 64 bytes for P-256) per IEEE P1363 and RFC 7518.
71
- **WebCrypto Native Rule:** In standard WebCrypto (`crypto.subtle.sign`),
72
ECDSA signatures are ALREADY emitted natively in raw IEEE P1363 format
73
(concatenated 32-byte `r` and `s` buffers, 64 bytes total). **DO NOT**
74
attempt DER-to-Raw conversion on `crypto.subtle.sign` outputs, as parsing a
75
64-byte raw buffer as ASN.1 DER causes an immediate runtime exception
76
(`Invalid DER sequence`). Directly base64url-encode the raw ArrayBuffer.
77
- **Legacy API Fallback:** If and only if implementing in legacy Java/Android
78
(`java.security.Signature`) or Node CommonJS (`crypto.createSign`), convert
79
ASN.1 DER output to raw 64-byte IEEE P1363 format before base64url encoding.
80
81
### E. SPA & Backend-for-Frontend (BFF) Architecture
82
83
- **Secretless SPAs Limitation:** Pure client-side single-page applications
84
(SPAs) without a backend cannot use DPoP directly with Google APIs due to
85
`client_secret` requirements on server endpoints and browser CORS
86
limitations on the `DPoP-Nonce` response header.
87
- **BFF Pattern:** To secure SPAs with DPoP, route authorization and token
88
refresh requests through a Backend-for-Frontend (BFF) server-side client.
89
The BFF sets `access_type=offline`, binds refresh tokens server-side using
90
DPoP, and maintains secure session cookies with the frontend.
91
92
## 2. Implementation Rules & Mandatory Public API
93
94
When creating new modules, your module MUST explicitly export all functions
95
below to integrate cleanly with CI/CD verification harnesses and automated
96
probers. When inspecting or refactoring existing codebases, ensure equivalent
97
cryptographic and RFC 9449 logic is present. Obey strict claim derivation logic
98
in all cases:
99
100
### A. DPoP Proof JWT Claim Derivation Rules (`createDPoPProof`)
101
102
When generating the DPoP Proof JWT in `createDPoPProof`:
103
104
**1. JOSE Header (`typ`, `alg`, `jwk`):**
105
```javascript
106
// Header
107
{
108
"typ": "dpop+jwt",
109
"alg": "ES256",
110
"jwk": await exportPublicJWK(publicKey)
111
}
112
```
113
114
**2. Payload Claims:**
115
- `"htm"`: Uppercase HTTP Method (`"POST"` for token requests).
116
- `"htu"`: Target URI stripped of query parameters and hash fragments using
117
`sanitizeHTU(htu)`. For token requests, this is
118
`https://oauth2.googleapis.com/token`.
119
- `"iat"`: Current integer epoch timestamp in seconds
120
(`Math.floor(Date.now() / 1000)`).
121
- `"jti"` (Critical Invariant):
122
1. If an explicit `jti` argument is provided to `createDPoPProof`, use that
123
exact string over all others.
124
2. Otherwise, if an `authCode` argument is provided (during initial code
125
exchange), set `jti = await calculateAuthCodeJti(authCode)` where
126
`calculateAuthCodeJti` computes `base64url(sha256(authCode))` to ensure
127
the DPoP proof is cryptographically bound to the authorization code.
128
3. Only if neither `jti` nor `authCode` is provided, generate a fresh
129
cryptographic random string via `generateRandomString()` (such as
130
`crypto.getRandomValues(new Uint8Array(24))` base64url encoded).
131
- `"ath"` (Optional): If an `accessToken` argument is provided for RFC 9449
132
resource requests, compute `base64url(sha256(accessToken))` via
133
`calculateATH(accessToken)` and inject it (RFC 9449 Section 6.1).
134
- `"nonce"` (Optional): If a `nonce` argument is provided, inject it directly
135
into the payload.
136
137
### B. Explicit Export Signatures
138
139
```javascript
140
// 1. Key generation & JWK export
141
export async function generateDPoPKeyPair() // -> { publicKey, privateKey } (private key extractable=false)
142
export async function exportPublicJWK(publicKey) // -> { kty: 'EC', crv: 'P-256', x, y }
143
144
// 2. Proof generation & validation
145
export async function createDPoPProof({ privateKey, publicKey, htm, htu, nonce, accessToken, authCode, jti }) // -> signed JWT string
146
export async function verifyDPoPProof(dpopProofJwt) // -> { isValid: boolean, header, payload, error }
147
export function sanitizeHTU(htu) // -> URL stripped of query and hash: const u = new URL(htu); return `${u.origin}${u.pathname}`;
148
149
// 3. Cryptographic & encoding utilities
150
export function base64UrlEncode(buffer) // -> Uint8Array/ArrayBuffer to base64url string without '=' padding
151
export function base64UrlDecode(str) // -> base64url string to Uint8Array/Buffer
152
export function stringToBase64Url(str) // -> UTF-8 string to base64url
153
export function base64UrlToString(str) // -> base64url to UTF-8 string
154
export function generateRandomString(byteLength = 32) // -> cryptographic random base64url string
155
export async function calculateATH(accessToken) // -> base64url(sha256(accessToken)) per RFC 9449 Sec 6.1
156
export async function calculateAuthCodeJti(code) // -> base64url(sha256(code))
157
export async function generatePKCE() // -> { codeVerifier (>=43 chars), codeChallenge, codeChallengeMethod: 'S256' }
158
```
159
160
## 3. Token Endpoint & Resource Request Workflow
161
162
When integrating with Google's OAuth 2.0 platform:
163
164
1. **Token Endpoint Requests (`oauth2.googleapis.com/token`):**
165
- Attach the DPoP Proof JWT in the `DPoP` HTTP header:
166
`` `DPoP: ${proofJwt}` `` when making `POST` requests for code exchange
167
(`grant_type=authorization_code`) and token refresh
168
(`grant_type=refresh_token`).
169
2. **Resource API Requests:**
170
- Google's token endpoint returns `"token_type": "Bearer"`. Downstream
171
requests to Google APIs (e.g. Calendar, Drive, Gmail) use standard
172
`` `Authorization: Bearer ${accessToken}` `` headers without DPoP
173
headers.
174
3. **Single-Retry Nonce Challenge Loop & Workflow Isolation:**
175
- If Google's token endpoint returns HTTP `400 Bad Request` with
176
`error: "use_dpop_nonce"` and a `"DPoP-Nonce"` response header:
177
- **Workflow Isolation:** Google's authorization server enforces
178
workflow isolation between authorization code exchange and token
179
refresh, returning an HTTP `400 use_dpop_nonce` challenge to
180
establish a fresh nonce namespace. This is standard RFC-compliant
181
protocol behavior, not a server failure.
182
- Cache the fresh nonce in client state (`this.dpopNonce`).
183
- Immediately synthesize a new DPoP Proof JWT incorporating the
184
updated `nonce` claim and a fresh `jti`.
185
- Replay the failed token request **exactly once**. If the retried
186
request fails, terminate immediately with an error to prevent
187
infinite recursion.
188
189
## 4. Concise Agent Egress Protocol
190
191
When prompted to synthesize or output code deliverables under this skill,
192
prioritize returning clean, directly importable code blocks without redundant
193
conversational preambles or repetitive filler. For conceptual or architectural
194
inquiries, provide standard direct answers.
195
196
## 5. References & Supporting Documentation
197
198
### Developer Documentation (Google for Developers)
199
- [DPoP Adoption Guide](https://developers.google.com/identity/protocols/oauth2/resources/dpop-adoption) —
200
Official Google Identity guide for implementing DPoP across authorization
201
code exchange and token refresh.
202
- [Using OAuth 2.0 for Web Server Applications](https://developers.google.com/identity/protocols/oauth2/web-server#offline) —
203
Offline access, refresh tokens, and server-side authorization flows.
204
- [OAuth 2.0 Best Practices: Sender-Constrain Tokens](https://developers.google.com/identity/protocols/oauth2/resources/best-practices#sender-constrain-tokens) —
205
Recommendations for token storage, rotation, and sender-constraining.
206
207
### Developer Knowledge MCP Server
208
- Agents equipped with Model Context Protocol (`MCP`) can query real-time
209
Google Developer documentation using the
210
[Google Developer Knowledge MCP Server](https://developers.google.com/knowledge/mcp)
211
(`npx -y @google/mcp-developer-knowledge-server`) via
212
`developer_knowledge:search_documents` and
213
`developer_knowledge:get_documents`.
214
215
### Standards & RFC Specifications
216
- [RFC 9449: OAuth 2.0 Demonstrating Proof-of-Possession (DPoP)](https://datatracker.ietf.org/doc/html/rfc9449)
217
- [RFC 7519: JSON Web Token (JWT)](https://datatracker.ietf.org/doc/html/rfc7519)
218
- [RFC 7636: Proof Key for Code Exchange by OAuth Public Clients (PKCE)](https://datatracker.ietf.org/doc/html/rfc7636)
219