@auth-craft/pages-auth-proxy 1.2.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +90 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/oauth-client.d.ts +33 -0
- package/dist/oauth-client.d.ts.map +1 -0
- package/dist/oauth-client.js +177 -0
- package/dist/oauth-client.js.map +1 -0
- package/dist/pages.d.ts +9 -3
- package/dist/pages.d.ts.map +1 -1
- package/dist/pages.js +9 -0
- package/dist/pages.js.map +1 -1
- package/dist/proxy.d.ts +30 -0
- package/dist/proxy.d.ts.map +1 -1
- package/dist/proxy.js +63 -20
- package/dist/proxy.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -78,6 +78,82 @@ const proxy = createAuthProxy({
|
|
|
78
78
|
export default { fetch: (req: Request) => proxy(req) };
|
|
79
79
|
```
|
|
80
80
|
|
|
81
|
+
## In front of the D1 Worker (no gateway)
|
|
82
|
+
|
|
83
|
+
The D1 auth Worker (`apps/auth-worker-d1`) serves `/{app}/...` itself, so point
|
|
84
|
+
`gateway` (Service Binding) or `gatewayUrl` straight at it; `edgeGateSecret` is not
|
|
85
|
+
needed. With `scope` locked, the Worker receives `/{scope}/auth/...` and treats every
|
|
86
|
+
request as that app. A client that also sends an `X-Auth-Context` naming another app is
|
|
87
|
+
refused with 400 `APP_CONFLICT` (the gateway used to overwrite the header instead). An
|
|
88
|
+
access token of another app is refused with 403 `TOKEN_APP_MISMATCH`.
|
|
89
|
+
|
|
90
|
+
## Storefront origin in emails (`originStampSecret`)
|
|
91
|
+
|
|
92
|
+
A platform serving many storefronts on their own domains under one `customer` app can
|
|
93
|
+
tell, in each email, which store the request came from. Set the same secret on the
|
|
94
|
+
proxy (`originStampSecret`, Pages env `ORIGIN_STAMP_SECRET`) and on the backend
|
|
95
|
+
(`ORIGIN_STAMP_SECRET`; on aws-cf-stack `LAMBDA_ORIGIN_STAMP_SECRET`). The proxy then
|
|
96
|
+
sends `X-Auth-Origin` — the origin of the URL Cloudflare routed to it, which the client
|
|
97
|
+
cannot choose — and `X-Origin-Stamp: <secret>`. The backend puts that origin in every
|
|
98
|
+
email it sends for the request as `variables.origin`. Whatever `X-Auth-Origin` /
|
|
99
|
+
`X-Origin-Stamp` the client sent is removed first, and the backend ignores the origin
|
|
100
|
+
when the stamp does not match. Check the value against your own domain list before
|
|
101
|
+
using it (name, logo, sender, links).
|
|
102
|
+
|
|
103
|
+
## A site customers do not sign in on (`allowedPaths`)
|
|
104
|
+
|
|
105
|
+
Lock the proxy to the paths the site needs; every other path gets a bare 404, so no
|
|
106
|
+
login form can post through that origin:
|
|
107
|
+
|
|
108
|
+
```ts
|
|
109
|
+
createAuthProxy({
|
|
110
|
+
scope: 'customer',
|
|
111
|
+
gateway: env.AUTH_GATEWAY,
|
|
112
|
+
originStampSecret: env.ORIGIN_STAMP_SECRET,
|
|
113
|
+
allowedPaths: ['/auth/refresh', '/auth/logout', '/auth/me'],
|
|
114
|
+
});
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
## Customers sign in on another origin (`oauthClient`)
|
|
118
|
+
|
|
119
|
+
A path is not a boundary: a script on any page of `shop.example` can draw a fake login
|
|
120
|
+
form at `shop.example/login` and call `/auth/refresh`. When your platform lets others run
|
|
121
|
+
scripts on a site, sign customers in on an origin you control (`account.shop.example`)
|
|
122
|
+
and make the site an OAuth 2.0 client (authorization code + PKCE). This proxy does the
|
|
123
|
+
client's part ([RFC 10017 §6.2](https://www.rfc-editor.org/rfc/rfc10017.html)):
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
// shop.example
|
|
127
|
+
createAuthProxy({
|
|
128
|
+
scope: 'customer',
|
|
129
|
+
gateway: env.AUTH_GATEWAY,
|
|
130
|
+
originStampSecret: env.ORIGIN_STAMP_SECRET,
|
|
131
|
+
allowedPaths: ['/auth/refresh', '/auth/logout', '/auth/me'],
|
|
132
|
+
// Or a function of the request, when one deployment serves many stores.
|
|
133
|
+
oauthClient: {
|
|
134
|
+
clientId: 'shop',
|
|
135
|
+
authorizeUrl: 'https://account.shop.example/login',
|
|
136
|
+
issuer: 'https://account.shop.example',
|
|
137
|
+
},
|
|
138
|
+
});
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
- Link to `/auth/login?returnTo=/cart`. The proxy sends the visitor to `authorizeUrl`.
|
|
142
|
+
- The sign-in page signs the customer in as usual, then calls
|
|
143
|
+
`client.auth.oauth2Authorize({ body })` with the query it was opened with and navigates
|
|
144
|
+
to `redirectTo`. `403 OAUTH_LOGIN_REQUIRED` means: sign in first. Serve that page with
|
|
145
|
+
`frame-ancestors 'none'` and no third-party script; its own proxy has no `oauthClient`.
|
|
146
|
+
- `/auth/callback` (register `https://shop.example/auth/callback` as the redirect URI)
|
|
147
|
+
exchanges the code, sets the HttpOnly refresh cookie and returns to the page. On
|
|
148
|
+
failure the page gets `?auth_error=<code>`.
|
|
149
|
+
|
|
150
|
+
The shop's session is an ordinary one (it refreshes at `/auth/refresh`, a sign-out ends
|
|
151
|
+
it), limited to what its scope opens: `profile` is `/auth/me`. Account settings are
|
|
152
|
+
refused there; customers change them on the account origin, signing in again.
|
|
153
|
+
|
|
154
|
+
Needs the app's token strategy `cookie`, `ORIGIN_STAMP_SECRET` on the backend, and an
|
|
155
|
+
`authClients` plugin there (`AUTH_CLIENTS_URL` on the prebuilt servers).
|
|
156
|
+
|
|
81
157
|
## Security notes
|
|
82
158
|
|
|
83
159
|
- **Not a CORS replacement — better.** Same-origin requests have no CORS at all. Site
|
|
@@ -89,4 +165,17 @@ export default { fetch: (req: Request) => proxy(req) };
|
|
|
89
165
|
even against one shared gateway worker. Use one locked proxy per app/scope.
|
|
90
166
|
- Keep `EDGE_GATE_SECRET` in a Pages **secret**. With a Service Binding you can configure
|
|
91
167
|
the gateway to trust the binding and avoid exposing the gate entirely.
|
|
92
|
-
- The proxy preserves method, body, headers and cookies
|
|
168
|
+
- The proxy preserves method, body, headers and cookies. It adds `X-Edge-Gate` and, with
|
|
169
|
+
`originStampSecret`, `X-Auth-Origin` and `X-Origin-Stamp`; those two are always removed
|
|
170
|
+
from what the client sent.
|
|
171
|
+
|
|
172
|
+
## Changelog
|
|
173
|
+
|
|
174
|
+
### 1.3.0
|
|
175
|
+
|
|
176
|
+
Additive. The new options need `@auth-craft/aws-cf-stack` 2.3.0 (backend and gateway),
|
|
177
|
+
`@auth-craft/worker-d1-stack` 0.3.0 or server-postgres 3.2.0.
|
|
178
|
+
|
|
179
|
+
- `originStampSecret` (Pages `ORIGIN_STAMP_SECRET`): stamps the origin the proxy was reached on. A client-sent `X-Auth-Origin` / `X-Origin-Stamp` is now always removed, with or without it.
|
|
180
|
+
- `allowedPaths`: only these paths are forwarded.
|
|
181
|
+
- `oauthClient`, `loginPath`, `callbackPath`: the site is an OAuth 2.0 client (authorization code + PKCE) of a sign-in page on another origin. Without `oauthClient`, `/auth/login` and `/auth/callback` are forwarded as before.
|
package/dist/index.d.ts
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
* Framework-agnostic core: `createAuthProxy`. For Cloudflare Pages Functions use the
|
|
9
9
|
* `@auth-craft/pages-auth-proxy/pages` subpath.
|
|
10
10
|
*/
|
|
11
|
+
export type { OAuthClientOptions, OAuthClientResolver } from './oauth-client.js';
|
|
11
12
|
export type { AuthProxyOptions, AuthScope, ProxyFetcher } from './proxy.js';
|
|
12
13
|
export { createAuthProxy } from './proxy.js';
|
|
13
14
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,YAAY,EAAE,gBAAgB,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAC5E,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,YAAY,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AACjF,YAAY,EAAE,gBAAgB,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAC5E,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC"}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAIH,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC"}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The proxy as an OAuth 2.0 client (RFC 10017 §6.2 token-mediating backend): a site whose
|
|
3
|
+
* customers sign in on another origin gets its session here, not in the page.
|
|
4
|
+
*
|
|
5
|
+
* `GET {loginPath}?returnTo=/x` → the sign-in page, with a PKCE authorization request.
|
|
6
|
+
* `GET {callbackPath}` → exchanges the code, sets the refresh cookie, → returnTo.
|
|
7
|
+
*
|
|
8
|
+
* The verifier and state live in an HttpOnly, encrypted, per-flow cookie: a script on the
|
|
9
|
+
* site can neither read nor replace them, so a code it gets hold of is useless.
|
|
10
|
+
*/
|
|
11
|
+
export interface OAuthClientOptions {
|
|
12
|
+
clientId: string;
|
|
13
|
+
/** The sign-in page that takes the authorization request, e.g. `https://account.shop.example/login`. */
|
|
14
|
+
authorizeUrl: string;
|
|
15
|
+
/** Expected `iss` of the response (RFC 9207): the sign-in page's origin. */
|
|
16
|
+
issuer: string;
|
|
17
|
+
/** @default 'profile' */
|
|
18
|
+
scope?: string;
|
|
19
|
+
}
|
|
20
|
+
/** One client, or the client of the host a request came to (`null`: none there). */
|
|
21
|
+
export type OAuthClientResolver = OAuthClientOptions | ((request: Request) => OAuthClientOptions | null | Promise<OAuthClientOptions | null>);
|
|
22
|
+
export interface OAuthClientDeps {
|
|
23
|
+
resolve: OAuthClientResolver;
|
|
24
|
+
loginPath: string;
|
|
25
|
+
callbackPath: string;
|
|
26
|
+
/** Key material for the flow cookie. */
|
|
27
|
+
secret: string;
|
|
28
|
+
/** POST the token request through the gateway, stamped with the request's origin. */
|
|
29
|
+
exchange: (request: Request, form: URLSearchParams) => Promise<Response>;
|
|
30
|
+
}
|
|
31
|
+
/** Answers the two paths; `null` for any other request. */
|
|
32
|
+
export declare function handleOAuthClient(request: Request, deps: OAuthClientDeps): Promise<Response | null>;
|
|
33
|
+
//# sourceMappingURL=oauth-client.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"oauth-client.d.ts","sourceRoot":"","sources":["../src/oauth-client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,MAAM,WAAW,kBAAkB;IACjC,QAAQ,EAAE,MAAM,CAAC;IACjB,wGAAwG;IACxG,YAAY,EAAE,MAAM,CAAC;IACrB,4EAA4E;IAC5E,MAAM,EAAE,MAAM,CAAC;IACf,yBAAyB;IACzB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,oFAAoF;AACpF,MAAM,MAAM,mBAAmB,GAC3B,kBAAkB,GAClB,CAAC,CAAC,OAAO,EAAE,OAAO,KAAK,kBAAkB,GAAG,IAAI,GAAG,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC,CAAC,CAAC;AAE3F,MAAM,WAAW,eAAe;IAC9B,OAAO,EAAE,mBAAmB,CAAC;IAC7B,SAAS,EAAE,MAAM,CAAC;IAClB,YAAY,EAAE,MAAM,CAAC;IACrB,wCAAwC;IACxC,MAAM,EAAE,MAAM,CAAC;IACf,qFAAqF;IACrF,QAAQ,EAAE,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,eAAe,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;CAC1E;AA2GD,2DAA2D;AAC3D,wBAAsB,iBAAiB,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,eAAe,GAAG,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,CAOzG"}
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The proxy as an OAuth 2.0 client (RFC 10017 §6.2 token-mediating backend): a site whose
|
|
3
|
+
* customers sign in on another origin gets its session here, not in the page.
|
|
4
|
+
*
|
|
5
|
+
* `GET {loginPath}?returnTo=/x` → the sign-in page, with a PKCE authorization request.
|
|
6
|
+
* `GET {callbackPath}` → exchanges the code, sets the refresh cookie, → returnTo.
|
|
7
|
+
*
|
|
8
|
+
* The verifier and state live in an HttpOnly, encrypted, per-flow cookie: a script on the
|
|
9
|
+
* site can neither read nor replace them, so a code it gets hold of is useless.
|
|
10
|
+
*/
|
|
11
|
+
const FLOW_SECONDS = 600;
|
|
12
|
+
const COOKIE = 'auth_flow_';
|
|
13
|
+
function base64url(bytes) {
|
|
14
|
+
let bin = '';
|
|
15
|
+
for (const b of bytes)
|
|
16
|
+
bin += String.fromCharCode(b);
|
|
17
|
+
return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
18
|
+
}
|
|
19
|
+
function fromBase64url(text) {
|
|
20
|
+
const bin = atob(text.replace(/-/g, '+').replace(/_/g, '/'));
|
|
21
|
+
return Uint8Array.from(bin, (c) => c.charCodeAt(0));
|
|
22
|
+
}
|
|
23
|
+
const random = () => base64url(crypto.getRandomValues(new Uint8Array(32)));
|
|
24
|
+
const utf8 = (text) => new TextEncoder().encode(text);
|
|
25
|
+
async function flowKey(secret) {
|
|
26
|
+
const material = await crypto.subtle.importKey('raw', utf8(secret), 'HKDF', false, ['deriveKey']);
|
|
27
|
+
return crypto.subtle.deriveKey({ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(0), info: utf8('pages-auth-proxy/oauth-flow') }, material, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
|
|
28
|
+
}
|
|
29
|
+
/** Bound to the site and client: one store's flow cookie means nothing at another's. */
|
|
30
|
+
const aad = (origin, clientId) => utf8(`${origin}\n${clientId}`);
|
|
31
|
+
async function seal(flow, secret, origin, clientId) {
|
|
32
|
+
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
33
|
+
const sealed = await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: aad(origin, clientId) }, await flowKey(secret), utf8(JSON.stringify(flow)));
|
|
34
|
+
return `${base64url(iv)}.${base64url(new Uint8Array(sealed))}`;
|
|
35
|
+
}
|
|
36
|
+
async function unseal(value, secret, origin, clientId) {
|
|
37
|
+
try {
|
|
38
|
+
const [iv, data] = value.split('.');
|
|
39
|
+
if (!iv || !data)
|
|
40
|
+
return null;
|
|
41
|
+
const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: fromBase64url(iv), additionalData: aad(origin, clientId) }, await flowKey(secret), fromBase64url(data));
|
|
42
|
+
return JSON.parse(new TextDecoder().decode(plain));
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/** A path on this origin, or '/': anything else would make sign-in an open redirect. */
|
|
49
|
+
function safeReturnTo(value, origin, own) {
|
|
50
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: control characters are what is being refused
|
|
51
|
+
if (!value?.startsWith('/') || value.startsWith('//') || /[\\\u0000-\u001f]/.test(value))
|
|
52
|
+
return '/';
|
|
53
|
+
try {
|
|
54
|
+
const url = new URL(value, origin);
|
|
55
|
+
if (url.origin !== origin || own.includes(url.pathname))
|
|
56
|
+
return '/';
|
|
57
|
+
return `${url.pathname}${url.search}${url.hash}`;
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
return '/';
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/** `__Host-` (Secure, host-only) except on plain-http localhost, where a browser refuses it. */
|
|
64
|
+
function cookie(url, state, value, maxAge) {
|
|
65
|
+
const secure = url.protocol === 'https:';
|
|
66
|
+
const name = `${secure ? '__Host-' : ''}${COOKIE}${state.slice(0, 16)}`;
|
|
67
|
+
return `${name}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${secure ? '; Secure' : ''}`;
|
|
68
|
+
}
|
|
69
|
+
function readCookie(request, url, state) {
|
|
70
|
+
const name = `${url.protocol === 'https:' ? '__Host-' : ''}${COOKIE}${state.slice(0, 16)}`;
|
|
71
|
+
for (const part of (request.headers.get('cookie') ?? '').split(';')) {
|
|
72
|
+
const eq = part.indexOf('=');
|
|
73
|
+
if (eq > 0 && part.slice(0, eq).trim() === name)
|
|
74
|
+
return part.slice(eq + 1).trim();
|
|
75
|
+
}
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
function redirect(location, setCookies = []) {
|
|
79
|
+
const headers = new Headers({ Location: location, 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer' });
|
|
80
|
+
for (const c of setCookies)
|
|
81
|
+
headers.append('Set-Cookie', c);
|
|
82
|
+
return new Response(null, { status: 303, headers });
|
|
83
|
+
}
|
|
84
|
+
/** Back to the site with the reason in `auth_error` (an OAuth error code). */
|
|
85
|
+
function failed(returnTo, origin, error, setCookies = []) {
|
|
86
|
+
const url = new URL(returnTo, origin);
|
|
87
|
+
url.searchParams.set('auth_error', /^[a-z_]{1,40}$/.test(error) ? error : 'server_error');
|
|
88
|
+
return redirect(`${url.pathname}${url.search}${url.hash}`, setCookies);
|
|
89
|
+
}
|
|
90
|
+
/** Answers the two paths; `null` for any other request. */
|
|
91
|
+
export async function handleOAuthClient(request, deps) {
|
|
92
|
+
const url = new URL(request.url);
|
|
93
|
+
if (url.pathname !== deps.loginPath && url.pathname !== deps.callbackPath)
|
|
94
|
+
return null;
|
|
95
|
+
if (request.method !== 'GET')
|
|
96
|
+
return new Response(null, { status: 405, headers: { Allow: 'GET' } });
|
|
97
|
+
const client = typeof deps.resolve === 'function' ? await deps.resolve(request) : deps.resolve;
|
|
98
|
+
if (!client)
|
|
99
|
+
return new Response(null, { status: 404 });
|
|
100
|
+
return url.pathname === deps.loginPath ? start(url, client, deps) : finish(request, url, client, deps);
|
|
101
|
+
}
|
|
102
|
+
async function start(url, client, deps) {
|
|
103
|
+
const flow = {
|
|
104
|
+
state: random(),
|
|
105
|
+
verifier: random(),
|
|
106
|
+
returnTo: safeReturnTo(url.searchParams.get('returnTo'), url.origin, [deps.loginPath, deps.callbackPath]),
|
|
107
|
+
expiresAt: Date.now() + FLOW_SECONDS * 1000,
|
|
108
|
+
};
|
|
109
|
+
const challenge = base64url(new Uint8Array(await crypto.subtle.digest('SHA-256', utf8(flow.verifier))));
|
|
110
|
+
const target = new URL(client.authorizeUrl);
|
|
111
|
+
for (const [key, value] of Object.entries({
|
|
112
|
+
response_type: 'code',
|
|
113
|
+
client_id: client.clientId,
|
|
114
|
+
redirect_uri: `${url.origin}${deps.callbackPath}`,
|
|
115
|
+
scope: client.scope ?? 'profile',
|
|
116
|
+
state: flow.state,
|
|
117
|
+
code_challenge: challenge,
|
|
118
|
+
code_challenge_method: 'S256',
|
|
119
|
+
})) {
|
|
120
|
+
target.searchParams.set(key, value);
|
|
121
|
+
}
|
|
122
|
+
const sealed = await seal(flow, deps.secret, url.origin, client.clientId);
|
|
123
|
+
return redirect(target.toString(), [cookie(url, flow.state, sealed, FLOW_SECONDS)]);
|
|
124
|
+
}
|
|
125
|
+
async function finish(request, url, client, deps) {
|
|
126
|
+
const param = (name) => {
|
|
127
|
+
const all = url.searchParams.getAll(name);
|
|
128
|
+
return all.length === 1 ? (all[0] ?? null) : null;
|
|
129
|
+
};
|
|
130
|
+
const state = param('state');
|
|
131
|
+
if (!state || !/^[A-Za-z0-9_-]{43}$/.test(state))
|
|
132
|
+
return failed('/', url.origin, 'invalid_request');
|
|
133
|
+
const sealed = readCookie(request, url, state);
|
|
134
|
+
const flow = sealed ? await unseal(sealed, deps.secret, url.origin, client.clientId) : null;
|
|
135
|
+
const clear = [cookie(url, state, '', 0)];
|
|
136
|
+
// Not a flow this browser started here (or an old one): nothing to exchange.
|
|
137
|
+
if (!flow || flow.state !== state || flow.expiresAt <= Date.now()) {
|
|
138
|
+
return failed('/', url.origin, 'invalid_request', clear);
|
|
139
|
+
}
|
|
140
|
+
// The answer of another authorization server (RFC 9207): its code must not be sent to ours.
|
|
141
|
+
if (param('iss') !== client.issuer)
|
|
142
|
+
return failed(flow.returnTo, url.origin, 'invalid_request', clear);
|
|
143
|
+
const error = param('error');
|
|
144
|
+
if (error)
|
|
145
|
+
return failed(flow.returnTo, url.origin, error, clear);
|
|
146
|
+
const code = param('code');
|
|
147
|
+
if (!code)
|
|
148
|
+
return failed(flow.returnTo, url.origin, 'invalid_request', clear);
|
|
149
|
+
const form = new URLSearchParams({
|
|
150
|
+
grant_type: 'authorization_code',
|
|
151
|
+
code,
|
|
152
|
+
client_id: client.clientId,
|
|
153
|
+
redirect_uri: `${url.origin}${deps.callbackPath}`,
|
|
154
|
+
code_verifier: flow.verifier,
|
|
155
|
+
});
|
|
156
|
+
let answer;
|
|
157
|
+
let body;
|
|
158
|
+
try {
|
|
159
|
+
answer = await deps.exchange(request, form);
|
|
160
|
+
body = (await answer.json());
|
|
161
|
+
}
|
|
162
|
+
catch {
|
|
163
|
+
return failed(flow.returnTo, url.origin, 'temporarily_unavailable', clear);
|
|
164
|
+
}
|
|
165
|
+
if (!answer.ok) {
|
|
166
|
+
const reason = typeof body.error === 'string' ? body.error : 'server_error';
|
|
167
|
+
return failed(flow.returnTo, url.origin, reason, clear);
|
|
168
|
+
}
|
|
169
|
+
const cookies = answer.headers.getSetCookie();
|
|
170
|
+
if (body.refresh_token !== undefined || cookies.length === 0) {
|
|
171
|
+
// Forwarding a refresh token would hand it to the page; dropping it would lose the session.
|
|
172
|
+
console.error("[pages-auth-proxy] oauthClient needs the app's token strategy to be 'cookie'");
|
|
173
|
+
return failed(flow.returnTo, url.origin, 'server_error', clear);
|
|
174
|
+
}
|
|
175
|
+
return redirect(flow.returnTo, [...clear, ...cookies]);
|
|
176
|
+
}
|
|
177
|
+
//# sourceMappingURL=oauth-client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"oauth-client.js","sourceRoot":"","sources":["../src/oauth-client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAkCH,MAAM,YAAY,GAAG,GAAG,CAAC;AACzB,MAAM,MAAM,GAAG,YAAY,CAAC;AAE5B,SAAS,SAAS,CAAC,KAAiB;IAClC,IAAI,GAAG,GAAG,EAAE,CAAC;IACb,KAAK,MAAM,CAAC,IAAI,KAAK;QAAE,GAAG,IAAI,MAAM,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC;IACrD,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;AAC9E,CAAC;AAED,SAAS,aAAa,CAAC,IAAY;IACjC,MAAM,GAAG,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC;IAC7D,OAAO,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC;AACtD,CAAC;AAED,MAAM,MAAM,GAAG,GAAG,EAAE,CAAC,SAAS,CAAC,MAAM,CAAC,eAAe,CAAC,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;AAC3E,MAAM,IAAI,GAAG,CAAC,IAAY,E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AC,IAAI,CAAC,QAAQ,EAAE,GAAG,CAAC,MAAM,EAAE,cAAc,EAAE,KAAK,CAAC,CAAC;IAClE,CAAC;IACD,OAAO,QAAQ,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC,GAAG,KAAK,EAAE,GAAG,OAAO,CAAC,CAAC,CAAC;AACzD,CAAC"}
|
package/dist/pages.d.ts
CHANGED
|
@@ -17,10 +17,12 @@
|
|
|
17
17
|
* - `AUTH_GATEWAY` — Service Binding to the gateway worker (preferred), OR
|
|
18
18
|
* - `AUTH_GATEWAY_URL` — gateway public URL (fallback when no Service Binding)
|
|
19
19
|
* - `EDGE_GATE_SECRET` — client→gateway gate (Pages secret)
|
|
20
|
+
* - `ORIGIN_STAMP_SECRET` — stamps this site's origin for the backend (Pages secret, optional)
|
|
20
21
|
*
|
|
21
22
|
* Anything outside `prefix` falls through to the rest of the Pages app via `next()`.
|
|
22
23
|
*/
|
|
23
|
-
import
|
|
24
|
+
import type { OAuthClientOptions } from './oauth-client.js';
|
|
25
|
+
import { type AuthProxyOptions, type AuthScope, type ProxyFetcher } from './proxy.js';
|
|
24
26
|
/** Env bindings this adapter reads from the Pages project. */
|
|
25
27
|
export interface PagesProxyEnv {
|
|
26
28
|
/** Service Binding to the gateway worker (preferred). */
|
|
@@ -29,6 +31,8 @@ export interface PagesProxyEnv {
|
|
|
29
31
|
AUTH_GATEWAY_URL?: string;
|
|
30
32
|
/** Client→gateway gate secret, sent as X-Edge-Gate. */
|
|
31
33
|
EDGE_GATE_SECRET?: string;
|
|
34
|
+
/** Shared with the backend; stamps X-Auth-Origin (see `originStampSecret`). */
|
|
35
|
+
ORIGIN_STAMP_SECRET?: string;
|
|
32
36
|
}
|
|
33
37
|
/** Minimal shape of a Pages Functions event context (avoids a hard dep on @cloudflare/workers-types consumers). */
|
|
34
38
|
interface PagesContext<Env extends PagesProxyEnv> {
|
|
@@ -36,7 +40,7 @@ interface PagesContext<Env extends PagesProxyEnv> {
|
|
|
36
40
|
env: Env;
|
|
37
41
|
next: () => Promise<Response>;
|
|
38
42
|
}
|
|
39
|
-
export interface CreatePagesAuthProxyOptions {
|
|
43
|
+
export interface CreatePagesAuthProxyOptions<Env extends PagesProxyEnv = PagesProxyEnv> extends Pick<AuthProxyOptions, 'allowedPaths' | 'loginPath' | 'callbackPath'> {
|
|
40
44
|
/**
|
|
41
45
|
* Lock this proxy to a single auth scope (recommended). The frontend then calls
|
|
42
46
|
* scope-less paths (e.g. `/auth/...`) and the proxy prepends the scope before
|
|
@@ -50,11 +54,13 @@ export interface CreatePagesAuthProxyOptions {
|
|
|
50
54
|
* '' (proxies everything the Function matches).
|
|
51
55
|
*/
|
|
52
56
|
prefix?: string;
|
|
57
|
+
/** See `AuthProxyOptions.oauthClient`; a function also gets the Pages `env`. */
|
|
58
|
+
oauthClient?: OAuthClientOptions | ((request: Request, env: Env) => OAuthClientOptions | null | Promise<OAuthClientOptions | null>);
|
|
53
59
|
}
|
|
54
60
|
/**
|
|
55
61
|
* Build a Pages Functions `onRequest` handler that proxies auth traffic to the gateway.
|
|
56
62
|
* Requests outside `prefix` are handed back to the Pages pipeline via `next()`.
|
|
57
63
|
*/
|
|
58
|
-
export declare function createPagesAuthProxy<Env extends PagesProxyEnv = PagesProxyEnv>(options?: CreatePagesAuthProxyOptions): (context: PagesContext<Env>) => Promise<Response>;
|
|
64
|
+
export declare function createPagesAuthProxy<Env extends PagesProxyEnv = PagesProxyEnv>(options?: CreatePagesAuthProxyOptions<Env>): (context: PagesContext<Env>) => Promise<Response>;
|
|
59
65
|
export {};
|
|
60
66
|
//# sourceMappingURL=pages.d.ts.map
|
package/dist/pages.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pages.d.ts","sourceRoot":"","sources":["../src/pages.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"pages.d.ts","sourceRoot":"","sources":["../src/pages.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;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CAAC,CA8BnD"}
|
package/dist/pages.js
CHANGED
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
* - `AUTH_GATEWAY` — Service Binding to the gateway worker (preferred), OR
|
|
18
18
|
* - `AUTH_GATEWAY_URL` — gateway public URL (fallback when no Service Binding)
|
|
19
19
|
* - `EDGE_GATE_SECRET` — client→gateway gate (Pages secret)
|
|
20
|
+
* - `ORIGIN_STAMP_SECRET` — stamps this site's origin for the backend (Pages secret, optional)
|
|
20
21
|
*
|
|
21
22
|
* Anything outside `prefix` falls through to the rest of the Pages app via `next()`.
|
|
22
23
|
*/
|
|
@@ -31,12 +32,20 @@ export function createPagesAuthProxy(options = {}) {
|
|
|
31
32
|
if (!env.AUTH_GATEWAY && !env.AUTH_GATEWAY_URL) {
|
|
32
33
|
throw new Error('pages-auth-proxy: bind AUTH_GATEWAY (Service Binding) or set AUTH_GATEWAY_URL in the Pages project.');
|
|
33
34
|
}
|
|
35
|
+
const { oauthClient } = options;
|
|
34
36
|
const proxy = createAuthProxy({
|
|
37
|
+
...(options.allowedPaths ? { allowedPaths: options.allowedPaths } : {}),
|
|
38
|
+
...(options.loginPath !== undefined ? { loginPath: options.loginPath } : {}),
|
|
39
|
+
...(options.callbackPath !== undefined ? { callbackPath: options.callbackPath } : {}),
|
|
40
|
+
...(oauthClient
|
|
41
|
+
? { oauthClient: typeof oauthClient === 'function' ? (r) => oauthClient(r, env) : oauthClient }
|
|
42
|
+
: {}),
|
|
35
43
|
...(options.scope !== undefined ? { scope: options.scope } : {}),
|
|
36
44
|
...(options.prefix !== undefined ? { prefix: options.prefix } : {}),
|
|
37
45
|
...(env.AUTH_GATEWAY ? { gateway: env.AUTH_GATEWAY } : {}),
|
|
38
46
|
...(env.AUTH_GATEWAY_URL ? { gatewayUrl: env.AUTH_GATEWAY_URL } : {}),
|
|
39
47
|
...(env.EDGE_GATE_SECRET ? { edgeGateSecret: env.EDGE_GATE_SECRET } : {}),
|
|
48
|
+
...(env.ORIGIN_STAMP_SECRET ? { originStampSecret: env.ORIGIN_STAMP_SECRET } : {}),
|
|
40
49
|
// Outside the prefix → let the rest of the Pages app handle it.
|
|
41
50
|
passthrough: () => next(),
|
|
42
51
|
});
|
package/dist/pages.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pages.js","sourceRoot":"","sources":["../src/pages.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"pages.js","sourceRoot":"","sources":["../src/pages.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAGH,OAAO,EAAyC,eAAe,EAAqB,MAAM,YAAY,CAAC;AA4CvG;;;GAGG;AACH,MAAM,UAAU,oBAAoB,CAClC,OAAO,GAAqC,EAAE;IAE9C,OAAO,KAAK,EAAE,OAA0B,EAAqB,EAAE;QAC7D,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,OAAO,CAAC;QAEvC,IAAI,CAAC,GAAG,CAAC,YAAY,IAAI,CAAC,GAAG,CAAC,gBAAgB,EAAE,CAAC;YAC/C,MAAM,IAAI,KAAK,CACb,qGAAqG,CACtG,CAAC;QACJ,CAAC;QAED,MAAM,EAAE,WAAW,EAAE,GAAG,OAAO,CAAC;QAChC,MAAM,KAAK,GAAG,eAAe,CAAC;YAC5B,GAAG,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,YAAY,EAAE,OAAO,CAAC,YAAY,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YACvE,GAAG,CAAC,OAAO,CAAC,SAAS,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,OAAO,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YAC5E,GAAG,CAAC,OAAO,CAAC,YAAY,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,YAAY,EAAE,OAAO,CAAC,YAAY,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YACrF,G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
17
17
|
* In-network, lowest latency, and `X-Edge-Gate` need not even be exposed.
|
|
18
18
|
* - HTTP: `gatewayUrl` is the gateway's public URL; the proxy fetches it directly.
|
|
19
19
|
*/
|
|
20
|
+
import { type OAuthClientResolver } from './oauth-client.js';
|
|
20
21
|
/** A minimal fetcher — a Cloudflare Service Binding satisfies this. */
|
|
21
22
|
export interface ProxyFetcher {
|
|
22
23
|
fetch(request: Request): Promise<Response>;
|
|
@@ -69,6 +70,35 @@ export interface AuthProxyOptions {
|
|
|
69
70
|
* Pages secret/env binding — never in client code.
|
|
70
71
|
*/
|
|
71
72
|
edgeGateSecret?: string;
|
|
73
|
+
/**
|
|
74
|
+
* Secret shared with the auth backend (`createAuthRouter({ originStampSecret })`,
|
|
75
|
+
* server env `ORIGIN_STAMP_SECRET`). When set, every forwarded request carries
|
|
76
|
+
* `X-Auth-Origin` — the origin of the URL this proxy was reached on, which the client
|
|
77
|
+
* cannot choose — and `X-Origin-Stamp` proving the proxy set it. The backend then
|
|
78
|
+
* puts that origin in every email it sends for the request (which store it is
|
|
79
|
+
* about). A client-sent `X-Auth-Origin` / `X-Origin-Stamp` is always removed. Keep it
|
|
80
|
+
* in a secret binding — never in client code.
|
|
81
|
+
*/
|
|
82
|
+
originStampSecret?: string;
|
|
83
|
+
/**
|
|
84
|
+
* Forward only these paths (exact, as the client calls them, e.g. '/auth/refresh');
|
|
85
|
+
* anything else under `prefix` gets a bare 404. For a site customers do not
|
|
86
|
+
* sign in on: `['/auth/refresh', '/auth/logout', '/auth/me']` — no login form can post
|
|
87
|
+
* through it.
|
|
88
|
+
*/
|
|
89
|
+
allowedPaths?: readonly string[];
|
|
90
|
+
/**
|
|
91
|
+
* Make this site an OAuth 2.0 client: customers sign in on another origin (one no
|
|
92
|
+
* third-party script runs on) and this proxy receives the session. It serves
|
|
93
|
+
* {@link loginPath} and {@link callbackPath} itself. Needs `scope` and
|
|
94
|
+
* `originStampSecret`, a backend with an `authClients` plugin, and the app's token
|
|
95
|
+
* strategy set to `cookie`. Pass a function when one deployment serves many hosts.
|
|
96
|
+
*/
|
|
97
|
+
oauthClient?: OAuthClientResolver;
|
|
98
|
+
/** Where a page sends a visitor to sign in (`?returnTo=/path`). @default '/auth/login' */
|
|
99
|
+
loginPath?: string;
|
|
100
|
+
/** Path of the redirect URI registered for the client. @default '/auth/callback' */
|
|
101
|
+
callbackPath?: string;
|
|
72
102
|
/**
|
|
73
103
|
* Response returned for requests outside `prefix`. Lets the proxy coexist with the
|
|
74
104
|
* app's own handlers. Defaults to a bare 404.
|
package/dist/proxy.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"proxy.d.ts","sourceRoot":"","sources":["../src/proxy.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,uEAAuE;AACvE,MAAM,WAAW,YAAY;IAC3B,KAAK,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;CAC5C;AAED;;;GAGG;AACH,MAAM,MAAM,SAAS,GAAG,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"proxy.d.ts","sourceRoot":"","sources":["../src/proxy.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,EAAqB,KAAK,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAEhF,uEAAuE;AACvE,MAAM,WAAW,YAAY;IAC3B,KAAK,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;CAC5C;AAED;;;GAGG;AACH,MAAM,MAAM,SAAS,GAAG,MAAM,CAAC;AAM/B,MAAM,WAAW,gBAAgB;IAC/B;;;;;;;;;;;;OAYG;IACH,KAAK,CAAC,EAAE,SAAS,CAAC;IAElB;;;;;;;;;OASG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAEhB;;;OAGG;IACH,OAAO,CAAC,EAAE,YAAY,CAAC;IAEvB;;;;OAIG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB;;;;OAIG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;IAExB;;;;;;;;OAQG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAE3B;;;;;OAKG;IACH,YAAY,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAEjC;;;;;;OAMG;IACH,WAAW,CAAC,EAAE,mBAAmB,CAAC;IAElC,0FAA0F;IAC1F,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB,oFAAoF;IACpF,YAAY,CAAC,EAAE,MAAM,CAAC;IAEtB;;;OAGG;IACH,WAAW,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,OAAO,CAAC,QAAQ,CAAC,GAAG,QAAQ,CAAC;CAClE;AA+CD;;;GAGG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,gBAAgB,GAAG,CAAC,OAAO,EAAE,OAAO,KAAK,OAAO,CAAC,QAAQ,CAAC,CA0ElG"}
|
package/dist/proxy.js
CHANGED
|
@@ -17,6 +17,8 @@
|
|
|
17
17
|
* In-network, lowest latency, and `X-Edge-Gate` need not even be exposed.
|
|
18
18
|
* - HTTP: `gatewayUrl` is the gateway's public URL; the proxy fetches it directly.
|
|
19
19
|
*/
|
|
20
|
+
import { handleOAuthClient } from './oauth-client.js';
|
|
21
|
+
const TOKEN_PATH = '/auth/oauth2/token';
|
|
20
22
|
const APP_ID_PATTERN = /^[a-z][a-z0-9-]{1,31}$/;
|
|
21
23
|
function normalizePrefix(prefix) {
|
|
22
24
|
if (!prefix)
|
|
@@ -33,10 +35,17 @@ function matchesPrefix(pathname, prefix) {
|
|
|
33
35
|
* Build the request forwarded to the gateway: same method/body/headers, with
|
|
34
36
|
* `X-Edge-Gate` attached. The path is preserved (the gateway derives + strips scope).
|
|
35
37
|
*/
|
|
36
|
-
function buildGatewayRequest(request,
|
|
38
|
+
function buildGatewayRequest(request, secrets, targetUrl) {
|
|
37
39
|
const headers = new Headers(request.headers);
|
|
38
|
-
if (edgeGateSecret)
|
|
39
|
-
headers.set('X-Edge-Gate', edgeGateSecret);
|
|
40
|
+
if (secrets.edgeGateSecret)
|
|
41
|
+
headers.set('X-Edge-Gate', secrets.edgeGateSecret);
|
|
42
|
+
// Only this proxy speaks for the origin: drop whatever the client sent.
|
|
43
|
+
headers.delete('X-Auth-Origin');
|
|
44
|
+
headers.delete('X-Origin-Stamp');
|
|
45
|
+
if (secrets.originStampSecret) {
|
|
46
|
+
headers.set('X-Auth-Origin', new URL(request.url).origin);
|
|
47
|
+
headers.set('X-Origin-Stamp', secrets.originStampSecret);
|
|
48
|
+
}
|
|
40
49
|
const init = {
|
|
41
50
|
method: request.method,
|
|
42
51
|
headers,
|
|
@@ -67,29 +76,63 @@ export function createAuthProxy(options) {
|
|
|
67
76
|
if (!options.gateway && !options.gatewayUrl) {
|
|
68
77
|
throw new Error('createAuthProxy: provide either `gateway` (Service Binding) or `gatewayUrl`.');
|
|
69
78
|
}
|
|
79
|
+
const { oauthClient, originStampSecret } = options;
|
|
80
|
+
if (oauthClient && (!scope || !originStampSecret)) {
|
|
81
|
+
throw new Error('createAuthProxy: oauthClient needs `scope` and `originStampSecret`.');
|
|
82
|
+
}
|
|
83
|
+
/** Send a request to the gateway on `path` of the scope. */
|
|
84
|
+
const forward = (request, path, search) => {
|
|
85
|
+
// Scope enforcement: prepend the locked scope segment so the gateway always sees
|
|
86
|
+
// `/{scope}{path}`. `path` is already normalized (`..` collapsed) by URL, so the
|
|
87
|
+
// client can't smuggle a different scope past this. When no scope is locked the path
|
|
88
|
+
// is forwarded unchanged (the client carries its own scope segment — legacy).
|
|
89
|
+
const forwardPath = scope ? `/${scope}${path}` : path;
|
|
90
|
+
if (options.gateway) {
|
|
91
|
+
// Service Binding path — forward to the bound worker on the (rewritten) path.
|
|
92
|
+
const target = new URL(request.url);
|
|
93
|
+
target.pathname = forwardPath;
|
|
94
|
+
target.search = search;
|
|
95
|
+
return options.gateway.fetch(buildGatewayRequest(request, options, target.toString()));
|
|
96
|
+
}
|
|
97
|
+
// HTTP path — rebuild against the gateway origin, preserving the (rewritten) path + query.
|
|
98
|
+
const target = new URL(`${options.gatewayUrl.replace(/\/$/, '')}${forwardPath}`);
|
|
99
|
+
target.search = search;
|
|
100
|
+
return fetch(buildGatewayRequest(request, options, target.toString()));
|
|
101
|
+
};
|
|
102
|
+
/** The token request: stamped with this site's origin, carrying none of the browser's cookies. */
|
|
103
|
+
const exchange = (request, form) => {
|
|
104
|
+
const headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' });
|
|
105
|
+
for (const name of ['user-agent', 'accept-language', 'cf-connecting-ip']) {
|
|
106
|
+
const value = request.headers.get(name);
|
|
107
|
+
if (value)
|
|
108
|
+
headers.set(name, value);
|
|
109
|
+
}
|
|
110
|
+
const url = new URL(TOKEN_PATH, request.url);
|
|
111
|
+
return forward(new Request(url, { method: 'POST', headers, body: form.toString() }), TOKEN_PATH, '');
|
|
112
|
+
};
|
|
70
113
|
return async (request) => {
|
|
71
114
|
const url = new URL(request.url);
|
|
115
|
+
if (oauthClient && originStampSecret) {
|
|
116
|
+
const answer = await handleOAuthClient(request, {
|
|
117
|
+
resolve: oauthClient,
|
|
118
|
+
loginPath: options.loginPath ?? '/auth/login',
|
|
119
|
+
callbackPath: options.callbackPath ?? '/auth/callback',
|
|
120
|
+
secret: originStampSecret,
|
|
121
|
+
exchange,
|
|
122
|
+
});
|
|
123
|
+
if (answer)
|
|
124
|
+
return answer;
|
|
125
|
+
// Only this proxy redeems codes: a page that could would be a client of its own.
|
|
126
|
+
if (url.pathname.replace(/\/+$/, '').endsWith(TOKEN_PATH))
|
|
127
|
+
return new Response(null, { status: 404 });
|
|
128
|
+
}
|
|
72
129
|
if (!matchesPrefix(url.pathname, prefix)) {
|
|
73
130
|
return passthrough(request);
|
|
74
131
|
}
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
// the client can't smuggle a different scope past this. When no scope is locked the
|
|
78
|
-
// path is forwarded unchanged (the client carries its own scope segment — legacy).
|
|
79
|
-
const forwardPath = scope ? `/${scope}${url.pathname}` : url.pathname;
|
|
80
|
-
// Service Binding path — forward to the bound worker on the (rewritten) path.
|
|
81
|
-
if (options.gateway) {
|
|
82
|
-
const target = new URL(url);
|
|
83
|
-
target.pathname = forwardPath;
|
|
84
|
-
const forwarded = buildGatewayRequest(request, options.edgeGateSecret, target.toString());
|
|
85
|
-
return options.gateway.fetch(forwarded);
|
|
132
|
+
if (options.allowedPaths && !options.allowedPaths.includes(url.pathname.replace(/\/+$/, ''))) {
|
|
133
|
+
return new Response(null, { status: 404 });
|
|
86
134
|
}
|
|
87
|
-
|
|
88
|
-
const base = options.gatewayUrl.endsWith('/') ? options.gatewayUrl.slice(0, -1) : options.gatewayUrl;
|
|
89
|
-
const target = new URL(`${base}${forwardPath}`);
|
|
90
|
-
target.search = url.search;
|
|
91
|
-
const forwarded = buildGatewayRequest(request, options.edgeGateSecret, target.toString());
|
|
92
|
-
return fetch(forwarded);
|
|
135
|
+
return forward(request, url.pathname, url.search);
|
|
93
136
|
};
|
|
94
137
|
}
|
|
95
138
|
//# sourceMappingURL=proxy.js.map
|
package/dist/proxy.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"proxy.js","sourceRoot":"","sources":["../src/proxy.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;
|
|
1
|
+
{"version":3,"file":"proxy.js","sourceRoot":"","sources":["../src/proxy.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,EAAE,iBAAiB,EAA4B,MAAM,mBAAmB,CAAC;AAahF,MAAM,UAAU,GAAG,oBAAoB,CAAC;AAExC,MAAM,cAAc,GAAG,wBAAwB,CAAC;AA2FhD,SAAS,eAAe,CAAC,MAA0B;IACjD,IAAI,CAAC,MAAM;QAAE,OAAO,EAAE,CAAC;IACvB,MAAM,CAAC,GAAG,M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AAC;YACzC,OAAO,WAAW,CAAC,OAAO,CAAC,CAAC;QAC9B,CAAC;QACD,IAAI,OAAO,CAAC,YAAY,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,QAAQ,CAAC,GAAG,CAAC,QAAQ,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC;YAC7F,OAAO,IAAI,QAAQ,CAAC,IAAI,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC;QAC7C,CAAC;QAED,OAAO,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC,QAAQ,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IACpD,CAAC,CAAC;AACJ,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@auth-craft/pages-auth-proxy",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.0",
|
|
4
4
|
"description": "Thin Cloudflare Pages reverse-proxy for Auth Craft — serves /{scope}/auth/* same-origin (first-party cookies) and forwards to the gateway worker (Service Binding or HTTP + X-Edge-Gate). Keeps all trust-critical logic in the gateway.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|