@sylphx/auth 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +53 -2
- package/dist/client.d.ts +19 -0
- package/dist/client.js +44 -0
- package/dist/email.d.ts +9 -0
- package/dist/email.js +156 -0
- package/dist/http.d.ts +26 -0
- package/dist/http.js +124 -0
- package/dist/server.d.ts +41 -0
- package/dist/server.js +287 -0
- package/dist/session.d.ts +12 -0
- package/dist/session.js +59 -0
- package/package.json +44 -5
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) Sylphx
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,54 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Sylphx Auth handler
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Mount the same Fetch handler on `/auth/*` in your server or worker. The host
|
|
4
|
+
supplies its public HTTPS origin and the instance ID, public slug, and
|
|
5
|
+
environment from Auth. Register the app origin as an Auth redirect origin.
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { createSylphxAuthHandler } from '@sylphx/auth'
|
|
9
|
+
|
|
10
|
+
export const handleAuth = createSylphxAuthHandler({
|
|
11
|
+
origin: 'https://app.example.com',
|
|
12
|
+
authApiOrigin: 'https://identity.example.net',
|
|
13
|
+
instance: { id: 'instance-id', slug: 'example', environment: 'production' },
|
|
14
|
+
defaultReturnTo: '/account',
|
|
15
|
+
})
|
|
16
|
+
|
|
17
|
+
// In your router: request => handleAuth(request)
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
This workspace package uses Web Fetch and Web Crypto, without framework or
|
|
21
|
+
Node imports. The runtime must supply an HTTPS origin and preserve individual
|
|
22
|
+
`Set-Cookie` headers. If terminating TLS in front of the handler, ensure its
|
|
23
|
+
Request URL reflects the trusted public origin, or supply `isPublicRequest`
|
|
24
|
+
with your edge's trusted-origin verification. Never trust caller-supplied
|
|
25
|
+
forwarded headers alone.
|
|
26
|
+
|
|
27
|
+
| Route | Method | Input / result |
|
|
28
|
+
| --- | --- | --- |
|
|
29
|
+
| `/auth/config` | GET | Public capabilities only; no credentials or upstream URLs |
|
|
30
|
+
| `/auth/start/:provider` | POST | JSON `{ next }` → `{ authorize }`; navigate to `authorize` |
|
|
31
|
+
| `/auth/callback` | GET | Auth's one-use ticket and the state bound to the start cookie |
|
|
32
|
+
| `/auth/email` | POST | Password, signup, email verification, email OTP, MFA, or passkey action |
|
|
33
|
+
| `/auth/logout` | POST | Revoke the presented session, then clear host-only cookies |
|
|
34
|
+
|
|
35
|
+
Use `@sylphx/auth-solid` for email and social UI, or its headless controller
|
|
36
|
+
for custom layouts. Mutation endpoints require a same-origin `Origin`.
|
|
37
|
+
`next` is always local; optionally restrict it further with `allowReturnTo`.
|
|
38
|
+
The default `__Host-auth_session` stores the Auth session in a Secure,
|
|
39
|
+
HttpOnly, SameSite=Lax cookie; the browser API never returns it in JSON.
|
|
40
|
+
Application server routes can present that session to Auth for validation.
|
|
41
|
+
The handler does not create application profiles or replace a session store.
|
|
42
|
+
|
|
43
|
+
For BYO OAuth, set `tenantAuthOrigin` to the exact origin of the verified
|
|
44
|
+
Account Portal. Auth discovery supplies the mount path. The server uses that
|
|
45
|
+
start URL and checks that the provider's `redirect_uri` points back to the
|
|
46
|
+
same mount; an unknown or unverified custom start is never followed. Shared
|
|
47
|
+
provider credentials still use the platform protocol callback. Auth owns
|
|
48
|
+
provider PKCE, OIDC nonce and Apple's `form_post`; the application callback
|
|
49
|
+
receives a GET with a one-use ticket, not raw provider credentials.
|
|
50
|
+
|
|
51
|
+
Install this package with your package manager. Use a registry version from the
|
|
52
|
+
shared clients release, and Node 22.12 or later (or a worker that supplies the
|
|
53
|
+
standard Fetch and Web Crypto APIs). The existing `@sylphx/sdk` and React imports
|
|
54
|
+
are unchanged.
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export declare const providers: {
|
|
2
|
+
readonly google: readonly ["Google", "https://accounts.google.com/o/oauth2/v2/auth"];
|
|
3
|
+
readonly github: readonly ["GitHub", "https://github.com/login/oauth/authorize"];
|
|
4
|
+
readonly apple: readonly ["Apple", "https://appleid.apple.com/auth/authorize"];
|
|
5
|
+
readonly facebook: readonly ["Facebook", "https://www.facebook.com/v25.0/dialog/oauth"];
|
|
6
|
+
readonly microsoft: readonly ["Microsoft", "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"];
|
|
7
|
+
};
|
|
8
|
+
export type Provider = keyof typeof providers;
|
|
9
|
+
export type EntryConfig = {
|
|
10
|
+
providers: Provider[];
|
|
11
|
+
password: boolean;
|
|
12
|
+
signup: boolean;
|
|
13
|
+
otp: boolean;
|
|
14
|
+
passkey: boolean;
|
|
15
|
+
};
|
|
16
|
+
export declare function isProvider(id: unknown): id is Provider;
|
|
17
|
+
export declare function providerDestination(id: Provider, location: unknown): string | undefined;
|
|
18
|
+
/** Never return an absolute or protocol-relative URL, even after normalization. */
|
|
19
|
+
export declare function safeReturnTo(value: unknown, fallback?: string): string;
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
export const providers = {
|
|
2
|
+
google: ['Google', 'https://accounts.google.com/o/oauth2/v2/auth'],
|
|
3
|
+
github: ['GitHub', 'https://github.com/login/oauth/authorize'],
|
|
4
|
+
apple: ['Apple', 'https://appleid.apple.com/auth/authorize'],
|
|
5
|
+
facebook: ['Facebook', 'https://www.facebook.com/v25.0/dialog/oauth'],
|
|
6
|
+
microsoft: ['Microsoft', 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize'],
|
|
7
|
+
};
|
|
8
|
+
export function isProvider(id) {
|
|
9
|
+
return typeof id === 'string' && Object.hasOwn(providers, id);
|
|
10
|
+
}
|
|
11
|
+
export function providerDestination(id, location) {
|
|
12
|
+
if (typeof location !== 'string')
|
|
13
|
+
return;
|
|
14
|
+
try {
|
|
15
|
+
const url = new URL(location);
|
|
16
|
+
if (url.origin + url.pathname === providers[id][1] &&
|
|
17
|
+
!url.username &&
|
|
18
|
+
!url.password &&
|
|
19
|
+
!url.hash)
|
|
20
|
+
return url.href;
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
// Invalid authorization location.
|
|
24
|
+
}
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
function relativePath(value) {
|
|
28
|
+
if (typeof value !== 'string' ||
|
|
29
|
+
value.length > 1024 ||
|
|
30
|
+
!value.startsWith('/') ||
|
|
31
|
+
value.startsWith('//') ||
|
|
32
|
+
value.includes('\\') ||
|
|
33
|
+
Array.from(value).some((c) => c.charCodeAt(0) <= 32 || c.charCodeAt(0) === 127) ||
|
|
34
|
+
/%(?:00|0a|0d|2f|5c)/i.test(value.split(/[?#]/, 1)[0]))
|
|
35
|
+
return undefined;
|
|
36
|
+
const url = new URL(value, 'https://return.invalid');
|
|
37
|
+
if (url.origin !== 'https://return.invalid' || url.pathname.startsWith('//'))
|
|
38
|
+
return undefined;
|
|
39
|
+
return url.pathname + url.search + url.hash;
|
|
40
|
+
}
|
|
41
|
+
/** Never return an absolute or protocol-relative URL, even after normalization. */
|
|
42
|
+
export function safeReturnTo(value, fallback = '/') {
|
|
43
|
+
return relativePath(value) ?? relativePath(fallback) ?? '/';
|
|
44
|
+
}
|
package/dist/email.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { type Data, type Identity } from './http.js';
|
|
2
|
+
import type { IssueSession } from './server.js';
|
|
3
|
+
export declare function refused(res: Response, error: string): Response;
|
|
4
|
+
export declare function emailEntry(identity: Identity, input: Data, next: string, ctx: {
|
|
5
|
+
origin: string;
|
|
6
|
+
loginPath: string;
|
|
7
|
+
instance: Record<string, string>;
|
|
8
|
+
session: IssueSession;
|
|
9
|
+
}): Promise<Response>;
|
package/dist/email.js
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { field, json, obj, problem, RANDOM, reply, token, } from './http.js';
|
|
2
|
+
const CODE = /^[0-9]{6}$/;
|
|
3
|
+
export function refused(res, error) {
|
|
4
|
+
return res.status === 429
|
|
5
|
+
? problem('try_later', 429)
|
|
6
|
+
: res.status >= 500
|
|
7
|
+
? problem('unavailable', 503)
|
|
8
|
+
: problem(error, 400);
|
|
9
|
+
}
|
|
10
|
+
export async function emailEntry(identity, input, next, ctx) {
|
|
11
|
+
const { origin, instance, session: issue } = ctx;
|
|
12
|
+
const rp = new URL(origin).hostname;
|
|
13
|
+
const action = input.action;
|
|
14
|
+
const email = field(input, 'email', 254)?.trim();
|
|
15
|
+
const password = field(input, 'password', 1024);
|
|
16
|
+
const code = field(input, 'code', 128);
|
|
17
|
+
let path;
|
|
18
|
+
let body = { session_mode: 'browser' };
|
|
19
|
+
const challengeId = field(input, 'challengeId', 200);
|
|
20
|
+
const secret = field(input, 'verification', 256);
|
|
21
|
+
const verification = token(challengeId) && token(secret)
|
|
22
|
+
? { idempotency_key: crypto.randomUUID(), challenge_id: challengeId, secret }
|
|
23
|
+
: undefined;
|
|
24
|
+
switch (action) {
|
|
25
|
+
case 'password':
|
|
26
|
+
case 'verify_signup': {
|
|
27
|
+
if (!email || !password)
|
|
28
|
+
return problem('invalid_input', 400);
|
|
29
|
+
if (action === 'verify_signup' && !verification)
|
|
30
|
+
return problem('verification_failed', 400);
|
|
31
|
+
path = '/v1/client/sign-in/password';
|
|
32
|
+
Object.assign(body, { email, password });
|
|
33
|
+
break;
|
|
34
|
+
}
|
|
35
|
+
case 'signup': {
|
|
36
|
+
if (!email ||
|
|
37
|
+
!password ||
|
|
38
|
+
new TextEncoder().encode(password).byteLength < 12 ||
|
|
39
|
+
new TextEncoder().encode(password).byteLength > 1024)
|
|
40
|
+
return problem('invalid_input', 400);
|
|
41
|
+
const target = new URL(ctx.loginPath, origin);
|
|
42
|
+
target.searchParams.set('next', next);
|
|
43
|
+
const res = await identity('/v1/client/sign-up', {
|
|
44
|
+
query: instance,
|
|
45
|
+
body: { email, password, redirect_url: target.href },
|
|
46
|
+
});
|
|
47
|
+
const data = await json(res);
|
|
48
|
+
return res.status === 202 && data.accepted === true
|
|
49
|
+
? reply({ step: 'check_email' }, 202)
|
|
50
|
+
: refused(res, 'signup_failed');
|
|
51
|
+
}
|
|
52
|
+
case 'otp_start':
|
|
53
|
+
if (!email)
|
|
54
|
+
return problem('invalid_input', 400);
|
|
55
|
+
path = '/v1/client/continue';
|
|
56
|
+
Object.assign(body, { email, method: 'email_otp' });
|
|
57
|
+
break;
|
|
58
|
+
case 'otp_verify': {
|
|
59
|
+
const flow = field(input, 'flow', 43);
|
|
60
|
+
if (!flow || !RANDOM.test(flow) || !code || !CODE.test(code))
|
|
61
|
+
return problem('invalid_code', 400);
|
|
62
|
+
path = '/v1/client/continue/verify';
|
|
63
|
+
body = { flow, code };
|
|
64
|
+
const factor = field(input, 'factor', 128);
|
|
65
|
+
if (factor && (input.method === 'totp' || input.method === 'recovery_code'))
|
|
66
|
+
body.factor_proofs = [{ factor_type: input.method, factor_id: '', response: factor }];
|
|
67
|
+
break;
|
|
68
|
+
}
|
|
69
|
+
case 'mfa': {
|
|
70
|
+
const challenge = field(input, 'challenge', 512);
|
|
71
|
+
if (!token(challenge) ||
|
|
72
|
+
!code ||
|
|
73
|
+
(input.method !== 'totp' && input.method !== 'recovery_code'))
|
|
74
|
+
return problem('invalid_code', 400);
|
|
75
|
+
path = '/v1/client/mfa/totp/verify';
|
|
76
|
+
body = { challenge, code, method: input.method };
|
|
77
|
+
break;
|
|
78
|
+
}
|
|
79
|
+
case 'passkey_start':
|
|
80
|
+
path = '/v1/client/sign-in/passkey/begin';
|
|
81
|
+
body = { rp_id: rp, origin };
|
|
82
|
+
break;
|
|
83
|
+
case 'passkey_verify':
|
|
84
|
+
path = '/v1/client/sign-in/passkey/verify';
|
|
85
|
+
for (const key of [
|
|
86
|
+
'challenge_id',
|
|
87
|
+
'credential_id',
|
|
88
|
+
'client_data_json',
|
|
89
|
+
'authenticator_data',
|
|
90
|
+
'signature',
|
|
91
|
+
]) {
|
|
92
|
+
const value = field(input, key, 3500);
|
|
93
|
+
if (!token(value))
|
|
94
|
+
return problem('invalid_input', 400);
|
|
95
|
+
body[key] = value;
|
|
96
|
+
}
|
|
97
|
+
if (token(input.user_handle))
|
|
98
|
+
body.user_handle = input.user_handle;
|
|
99
|
+
break;
|
|
100
|
+
default:
|
|
101
|
+
return problem('not_found', 404);
|
|
102
|
+
}
|
|
103
|
+
const res = await identity(path, { query: instance, body });
|
|
104
|
+
const data = await json(res);
|
|
105
|
+
if (res.status === 401 && data.code === 'mfa_required') {
|
|
106
|
+
if ((action === 'password' || action === 'verify_signup') && token(data.mfa_challenge))
|
|
107
|
+
return reply({ step: 'mfa', challenge: data.mfa_challenge });
|
|
108
|
+
if (action === 'otp_verify' && !input.factor)
|
|
109
|
+
return reply({ step: 'mfa' });
|
|
110
|
+
}
|
|
111
|
+
if (!res.ok)
|
|
112
|
+
return refused(res, action === 'password' || action === 'verify_signup'
|
|
113
|
+
? 'invalid_credentials'
|
|
114
|
+
: action === 'mfa' || action === 'otp_verify'
|
|
115
|
+
? 'invalid_code'
|
|
116
|
+
: 'method_unavailable');
|
|
117
|
+
if (action === 'otp_start' &&
|
|
118
|
+
data.step === 'email_otp' &&
|
|
119
|
+
typeof data.flow === 'string' &&
|
|
120
|
+
RANDOM.test(data.flow))
|
|
121
|
+
return reply({ flow: data.flow });
|
|
122
|
+
if (action === 'passkey_start' &&
|
|
123
|
+
data.rp_id === rp &&
|
|
124
|
+
token(data.challenge) &&
|
|
125
|
+
token(data.challenge_id) &&
|
|
126
|
+
Array.isArray(data.allowed_credential_ids) &&
|
|
127
|
+
data.allowed_credential_ids.every(token))
|
|
128
|
+
return reply({
|
|
129
|
+
challenge: data.challenge,
|
|
130
|
+
challengeId: data.challenge_id,
|
|
131
|
+
rpId: rp,
|
|
132
|
+
credentials: data.allowed_credential_ids,
|
|
133
|
+
});
|
|
134
|
+
if (action === 'otp_start' || action === 'passkey_start')
|
|
135
|
+
return problem('unavailable', 502);
|
|
136
|
+
const session = obj(data.session);
|
|
137
|
+
const credential = session.token;
|
|
138
|
+
const user = obj(data.user);
|
|
139
|
+
if (!token(credential) || !token(user.id))
|
|
140
|
+
return problem('unavailable', 502);
|
|
141
|
+
if (verification && (action === 'verify_signup' || action === 'mfa')) {
|
|
142
|
+
// Require both the password session and mail proof. Auth binds them to
|
|
143
|
+
// the same principal and preserves the registrant's chosen password.
|
|
144
|
+
const confirmed = await identity('/v1/email-verification/complete', {
|
|
145
|
+
bearer: credential,
|
|
146
|
+
body: verification,
|
|
147
|
+
});
|
|
148
|
+
const result = await json(confirmed);
|
|
149
|
+
if (!confirmed.ok || obj(result.verification).principal_id !== user.id)
|
|
150
|
+
return refused(confirmed, 'verification_failed');
|
|
151
|
+
}
|
|
152
|
+
else if (user.email_verified !== true)
|
|
153
|
+
return problem('verify_email', 403);
|
|
154
|
+
const cookies = await issue({ token: credential, expiresAt: session.expires_at });
|
|
155
|
+
return cookies ? reply({ next }, 200, cookies) : problem('session_unavailable', 502);
|
|
156
|
+
}
|
package/dist/http.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export type Data = Record<string, unknown>;
|
|
2
|
+
export type AuthCookie = readonly [name: string, value: string, seconds: number];
|
|
3
|
+
export type AuthFetch = (input: URL, init: RequestInit) => Promise<Response>;
|
|
4
|
+
export declare const RANDOM: RegExp;
|
|
5
|
+
export declare function obj(value: unknown): Data;
|
|
6
|
+
export declare function token(value: unknown): value is string;
|
|
7
|
+
export declare function field(data: Data, key: string, max: number): string | undefined;
|
|
8
|
+
export declare function headers(cookies?: readonly AuthCookie[]): Headers;
|
|
9
|
+
export declare function reply(data: unknown, status?: number, cookies?: readonly AuthCookie[]): Response;
|
|
10
|
+
export declare function problem(error: string, status: number): Response;
|
|
11
|
+
export declare function redirect(location: string, cookies: readonly AuthCookie[]): Response;
|
|
12
|
+
export declare function json(response: Response): Promise<Data>;
|
|
13
|
+
export declare function discard(response: Response): void;
|
|
14
|
+
export declare function readCookie(request: Request, name: string): string | undefined;
|
|
15
|
+
export declare function cookieName(value: string): string;
|
|
16
|
+
export declare function random(): string;
|
|
17
|
+
export declare function pkceChallenge(verifier: string): Promise<string>;
|
|
18
|
+
export declare function transport(request: Request, fetchUpstream: AuthFetch, api: string): (path: string | URL, options?: {
|
|
19
|
+
query?: Record<string, string>;
|
|
20
|
+
body?: Data | URLSearchParams;
|
|
21
|
+
bearer?: string;
|
|
22
|
+
method?: "GET" | "POST";
|
|
23
|
+
manual?: boolean;
|
|
24
|
+
}) => Promise<Response>;
|
|
25
|
+
export type Identity = ReturnType<typeof transport>;
|
|
26
|
+
export declare function jsonBody(request: Request): Promise<Record<string, unknown>>;
|
package/dist/http.js
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
export const RANDOM = /^[A-Za-z0-9_-]{43}$/;
|
|
2
|
+
const TOKEN = /^[A-Za-z0-9._~-]{1,3500}$/;
|
|
3
|
+
export function obj(value) {
|
|
4
|
+
return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
|
5
|
+
}
|
|
6
|
+
export function token(value) {
|
|
7
|
+
return typeof value === 'string' && TOKEN.test(value);
|
|
8
|
+
}
|
|
9
|
+
export function field(data, key, max) {
|
|
10
|
+
const value = data[key];
|
|
11
|
+
return typeof value === 'string' && value.length > 0 && value.length <= max ? value : undefined;
|
|
12
|
+
}
|
|
13
|
+
export function headers(cookies = []) {
|
|
14
|
+
const out = new Headers({
|
|
15
|
+
'Cache-Control': 'private, no-store',
|
|
16
|
+
'Referrer-Policy': 'no-referrer',
|
|
17
|
+
'X-Content-Type-Options': 'nosniff',
|
|
18
|
+
});
|
|
19
|
+
for (const [name, value, seconds] of cookies) {
|
|
20
|
+
out.append('Set-Cookie', `${name}=${value}; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=${seconds}`);
|
|
21
|
+
}
|
|
22
|
+
return out;
|
|
23
|
+
}
|
|
24
|
+
export function reply(data, status = 200, cookies) {
|
|
25
|
+
return Response.json(data, { status, headers: headers(cookies) });
|
|
26
|
+
}
|
|
27
|
+
export function problem(error, status) {
|
|
28
|
+
return reply({ error }, status);
|
|
29
|
+
}
|
|
30
|
+
export function redirect(location, cookies) {
|
|
31
|
+
const out = headers(cookies);
|
|
32
|
+
out.set('Location', location);
|
|
33
|
+
return new Response(null, { status: 303, headers: out });
|
|
34
|
+
}
|
|
35
|
+
export async function json(response) {
|
|
36
|
+
if (!/^application\/(?:problem\+)?json\b/i.test(response.headers.get('content-type') ?? '')) {
|
|
37
|
+
discard(response);
|
|
38
|
+
throw new Error('Unexpected authentication response');
|
|
39
|
+
}
|
|
40
|
+
return obj(await response.json());
|
|
41
|
+
}
|
|
42
|
+
export function discard(response) {
|
|
43
|
+
void response.body?.cancel().catch(() => undefined);
|
|
44
|
+
}
|
|
45
|
+
export function readCookie(request, name) {
|
|
46
|
+
const candidates = (request.headers.get('cookie') ?? '')
|
|
47
|
+
.split(';')
|
|
48
|
+
.map((part) => part.trim())
|
|
49
|
+
.filter((part) => part.startsWith(`${name}=`));
|
|
50
|
+
return candidates.length === 1 ? candidates[0]?.slice(name.length + 1) : undefined;
|
|
51
|
+
}
|
|
52
|
+
export function cookieName(value) {
|
|
53
|
+
if (!/^[A-Za-z0-9_-]{1,128}$/.test(value))
|
|
54
|
+
throw new TypeError('Invalid cookie name');
|
|
55
|
+
return value;
|
|
56
|
+
}
|
|
57
|
+
export function random() {
|
|
58
|
+
return base64url(crypto.getRandomValues(new Uint8Array(32)));
|
|
59
|
+
}
|
|
60
|
+
function base64url(bytes) {
|
|
61
|
+
return btoa(String.fromCharCode(...bytes))
|
|
62
|
+
.replace(/\+/g, '-')
|
|
63
|
+
.replace(/\//g, '_')
|
|
64
|
+
.replace(/=+$/, '');
|
|
65
|
+
}
|
|
66
|
+
export async function pkceChallenge(verifier) {
|
|
67
|
+
return base64url(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))));
|
|
68
|
+
}
|
|
69
|
+
export function transport(request, fetchUpstream, api) {
|
|
70
|
+
return (path, options = {}) => {
|
|
71
|
+
const url = new URL(path, api);
|
|
72
|
+
for (const [key, value] of Object.entries(options.query ?? {}))
|
|
73
|
+
url.searchParams.set(key, value);
|
|
74
|
+
const out = new Headers({ Accept: 'application/json' });
|
|
75
|
+
const ua = request.headers.get('user-agent');
|
|
76
|
+
if (ua)
|
|
77
|
+
out.set('User-Agent', ua);
|
|
78
|
+
if (options.bearer)
|
|
79
|
+
out.set('Authorization', `Bearer ${options.bearer}`);
|
|
80
|
+
const body = options.body instanceof URLSearchParams
|
|
81
|
+
? options.body
|
|
82
|
+
: options.body && JSON.stringify(options.body);
|
|
83
|
+
if (typeof body === 'string')
|
|
84
|
+
out.set('Content-Type', 'application/json');
|
|
85
|
+
return fetchUpstream(url, {
|
|
86
|
+
method: options.method ?? (options.body ? 'POST' : 'GET'),
|
|
87
|
+
headers: out,
|
|
88
|
+
body: body ?? null,
|
|
89
|
+
credentials: 'omit',
|
|
90
|
+
redirect: options.manual ? 'manual' : 'error',
|
|
91
|
+
cache: 'no-store',
|
|
92
|
+
signal: AbortSignal.any([request.signal, AbortSignal.timeout(10_000)]),
|
|
93
|
+
});
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
const MAX_JSON = 32_768;
|
|
97
|
+
export async function jsonBody(request) {
|
|
98
|
+
const reader = request.body?.getReader();
|
|
99
|
+
if (!reader)
|
|
100
|
+
throw new Error('Missing JSON body');
|
|
101
|
+
const decoder = new TextDecoder('utf-8', { fatal: true });
|
|
102
|
+
let body = '';
|
|
103
|
+
let bytes = 0;
|
|
104
|
+
try {
|
|
105
|
+
while (true) {
|
|
106
|
+
const { done, value } = await reader.read();
|
|
107
|
+
if (done)
|
|
108
|
+
break;
|
|
109
|
+
bytes += value.byteLength;
|
|
110
|
+
if (bytes > MAX_JSON)
|
|
111
|
+
throw new Error('JSON body too large');
|
|
112
|
+
body += decoder.decode(value, { stream: true });
|
|
113
|
+
}
|
|
114
|
+
body += decoder.decode();
|
|
115
|
+
const parsed = JSON.parse(body);
|
|
116
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
117
|
+
throw new Error('Invalid JSON');
|
|
118
|
+
return parsed;
|
|
119
|
+
}
|
|
120
|
+
finally {
|
|
121
|
+
void reader.cancel().catch(() => undefined);
|
|
122
|
+
reader.releaseLock();
|
|
123
|
+
}
|
|
124
|
+
}
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { type Provider } from './client.js';
|
|
2
|
+
import { type AuthCookie, type AuthFetch } from './http.js';
|
|
3
|
+
export type { AuthCookie, AuthFetch } from './http.js';
|
|
4
|
+
export { jsonBody as readAuthJson } from './http.js';
|
|
5
|
+
export { exchangeManagementSession } from './session.js';
|
|
6
|
+
export type IdentitySession = {
|
|
7
|
+
token: string;
|
|
8
|
+
expiresAt: unknown;
|
|
9
|
+
};
|
|
10
|
+
export type IssueSession = (session: IdentitySession) => Promise<readonly AuthCookie[] | undefined>;
|
|
11
|
+
type SessionAdapter = {
|
|
12
|
+
issue(session: IdentitySession, request: Request): ReturnType<IssueSession>;
|
|
13
|
+
logout(request: Request): Promise<Response>;
|
|
14
|
+
};
|
|
15
|
+
export type SylphxAuthOptions = {
|
|
16
|
+
/** Trusted public origin serving the application, never an unvalidated Host header. */
|
|
17
|
+
origin: string;
|
|
18
|
+
/** Trusted Auth API origin. Only the handler sees this value. */
|
|
19
|
+
authApiOrigin: string;
|
|
20
|
+
instance: {
|
|
21
|
+
slug: string;
|
|
22
|
+
id: string;
|
|
23
|
+
environment: string;
|
|
24
|
+
};
|
|
25
|
+
/** Pin the origin of the tenant's verified Account Portal for BYO OAuth. Auth discovers its mount path. */
|
|
26
|
+
tenantAuthOrigin?: string;
|
|
27
|
+
providers?: readonly Provider[];
|
|
28
|
+
/** Transitional alias for a preexisting client that posts action and provider to /auth/start. */
|
|
29
|
+
legacyStart?: boolean;
|
|
30
|
+
loginPath?: string;
|
|
31
|
+
defaultReturnTo?: string;
|
|
32
|
+
allowReturnTo?: (path: string) => boolean;
|
|
33
|
+
flowCookie?: string;
|
|
34
|
+
sessionCookie?: string;
|
|
35
|
+
/** For an existing edge: check a trusted host binding on the internal request. */
|
|
36
|
+
isPublicRequest?: (request: Request) => boolean;
|
|
37
|
+
/** Only for hosts with an existing authoritative session and revocation mechanism. */
|
|
38
|
+
session?: SessionAdapter;
|
|
39
|
+
fetch?: AuthFetch;
|
|
40
|
+
};
|
|
41
|
+
export declare function createSylphxAuthHandler(options: SylphxAuthOptions): (request: Request) => Promise<Response>;
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
import { isProvider, providerDestination, providers, safeReturnTo, } from './client.js';
|
|
2
|
+
import { emailEntry } from './email.js';
|
|
3
|
+
import { cookieName, discard, field, headers, json, jsonBody, obj, problem, RANDOM, random, readCookie, redirect, reply, token, transport, } from './http.js';
|
|
4
|
+
export { jsonBody as readAuthJson } from './http.js';
|
|
5
|
+
export { exchangeManagementSession } from './session.js';
|
|
6
|
+
const FLOW_AGE = 600;
|
|
7
|
+
const START = '/auth/start/';
|
|
8
|
+
const CALLBACK = '/auth/callback';
|
|
9
|
+
function secureUrl(value) {
|
|
10
|
+
if (typeof value !== 'string')
|
|
11
|
+
return;
|
|
12
|
+
try {
|
|
13
|
+
const url = new URL(value);
|
|
14
|
+
if (url.protocol === 'https:' && !url.username && !url.password && !url.hash)
|
|
15
|
+
return url;
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
// Unusable URL.
|
|
19
|
+
}
|
|
20
|
+
return undefined;
|
|
21
|
+
}
|
|
22
|
+
function requireOrigin(value) {
|
|
23
|
+
const url = secureUrl(value);
|
|
24
|
+
if (!url || url.pathname !== '/' || url.search)
|
|
25
|
+
throw new TypeError('Expected a trusted HTTPS origin');
|
|
26
|
+
return url.origin;
|
|
27
|
+
}
|
|
28
|
+
function portalStart(provider, row, discovery, pin, slug) {
|
|
29
|
+
// This is a server-side fetch target, not a URL forwarded from a request.
|
|
30
|
+
const url = secureUrl(row.start_url);
|
|
31
|
+
const mount = secureUrl(discovery.portal_url);
|
|
32
|
+
const mountPath = mount?.pathname.replace(/\/$/, '');
|
|
33
|
+
if (!pin ||
|
|
34
|
+
discovery.portal_origin !== pin ||
|
|
35
|
+
!url ||
|
|
36
|
+
!mount ||
|
|
37
|
+
mount.search ||
|
|
38
|
+
url.origin !== pin ||
|
|
39
|
+
mount.origin !== pin ||
|
|
40
|
+
url.pathname !== `${mountPath}/oauth/${provider}/start` ||
|
|
41
|
+
url.searchParams.size !== 1 ||
|
|
42
|
+
url.searchParams.get('instance') !== slug)
|
|
43
|
+
return;
|
|
44
|
+
return { url, redirectUri: `${mount.origin + mountPath}/oauth/callback` };
|
|
45
|
+
}
|
|
46
|
+
export function createSylphxAuthHandler(options) {
|
|
47
|
+
const origin = requireOrigin(options.origin);
|
|
48
|
+
const api = requireOrigin(options.authApiOrigin);
|
|
49
|
+
const tenantAuthOrigin = options.tenantAuthOrigin === undefined ? undefined : requireOrigin(options.tenantAuthOrigin);
|
|
50
|
+
if (tenantAuthOrigin && tenantAuthOrigin === api)
|
|
51
|
+
throw new TypeError('Use the tenant Auth origin, not the Auth API origin');
|
|
52
|
+
const { slug, id, environment } = options.instance;
|
|
53
|
+
if (!/^[a-z0-9][a-z0-9-]{0,62}$/.test(slug) || !id || !environment)
|
|
54
|
+
throw new TypeError('Expected an Auth instance');
|
|
55
|
+
const instance = { instance: slug };
|
|
56
|
+
const loginPath = safeReturnTo(options.loginPath, '/login');
|
|
57
|
+
if (/[?#]/.test(loginPath))
|
|
58
|
+
throw new TypeError('Expected a login pathname');
|
|
59
|
+
const fallback = safeReturnTo(options.defaultReturnTo);
|
|
60
|
+
const nextPath = (value) => {
|
|
61
|
+
const next = safeReturnTo(value, fallback);
|
|
62
|
+
return options.allowReturnTo && !options.allowReturnTo(next) ? fallback : next;
|
|
63
|
+
};
|
|
64
|
+
const flowName = cookieName(options.flowCookie ?? '__Host-auth_flow');
|
|
65
|
+
const sessionName = cookieName(options.sessionCookie ?? '__Host-auth_session');
|
|
66
|
+
if (flowName === sessionName ||
|
|
67
|
+
![flowName, sessionName].every((name) => name.startsWith('__Host-')))
|
|
68
|
+
throw new TypeError('Use separate host-only cookie names');
|
|
69
|
+
const clearFlow = [flowName, '', 0];
|
|
70
|
+
const callback = origin + CALLBACK;
|
|
71
|
+
const fetchUpstream = options.fetch ?? ((url, init) => fetch(url, init));
|
|
72
|
+
const social = [...new Set(options.providers ?? Object.keys(providers).filter(isProvider))];
|
|
73
|
+
async function discover(identity) {
|
|
74
|
+
const res = await identity('/v1/client/config', { query: instance });
|
|
75
|
+
const data = await json(res);
|
|
76
|
+
const resolved = obj(data.instance);
|
|
77
|
+
if (!res.ok ||
|
|
78
|
+
resolved.id !== id ||
|
|
79
|
+
resolved.slug !== slug ||
|
|
80
|
+
resolved.environment !== environment)
|
|
81
|
+
throw new Error('Unexpected authentication instance');
|
|
82
|
+
const methods = obj(data.methods);
|
|
83
|
+
const redirects = new Map();
|
|
84
|
+
const rows = Array.isArray(data.social) ? data.social.map(obj) : [];
|
|
85
|
+
for (const provider of social) {
|
|
86
|
+
const entries = rows.filter((row) => row.provider === provider);
|
|
87
|
+
if (entries.length !== 1)
|
|
88
|
+
continue;
|
|
89
|
+
const row = entries[0];
|
|
90
|
+
if (row.credentials === 'shared')
|
|
91
|
+
redirects.set(provider, null);
|
|
92
|
+
else if (row.credentials === 'custom') {
|
|
93
|
+
const start = portalStart(provider, row, data, tenantAuthOrigin, slug);
|
|
94
|
+
if (start)
|
|
95
|
+
redirects.set(provider, start);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
const config = {
|
|
99
|
+
providers: [...redirects.keys()],
|
|
100
|
+
password: methods.password === true,
|
|
101
|
+
signup: methods.sign_up === true && methods.password === true,
|
|
102
|
+
otp: methods.email_otp === true,
|
|
103
|
+
passkey: methods.passkey === true,
|
|
104
|
+
};
|
|
105
|
+
return { config, redirects };
|
|
106
|
+
}
|
|
107
|
+
async function start(identity, provider, next) {
|
|
108
|
+
if (!isProvider(provider) || !social.includes(provider))
|
|
109
|
+
return problem('unknown_provider', 400);
|
|
110
|
+
const { redirects } = await discover(identity);
|
|
111
|
+
const start = redirects.get(provider);
|
|
112
|
+
if (start === undefined)
|
|
113
|
+
return problem('method_unavailable', 403);
|
|
114
|
+
const state = random();
|
|
115
|
+
const target = new URL(callback);
|
|
116
|
+
target.searchParams.set('flow', state);
|
|
117
|
+
// Auth owns upstream PKCE S256, nonce and Apple's form_post. This
|
|
118
|
+
// app's GET callback only receives Auth's one-use sign-in ticket.
|
|
119
|
+
const res = await identity(start?.url ?? `/v1/client/oauth/${provider}/start`, {
|
|
120
|
+
query: { ...instance, redirect_url: target.href, session_mode: 'browser' },
|
|
121
|
+
manual: true,
|
|
122
|
+
});
|
|
123
|
+
const authorize = res.status === 303 && providerDestination(provider, res.headers.get('location'));
|
|
124
|
+
discard(res);
|
|
125
|
+
if (!authorize)
|
|
126
|
+
return problem('method_unavailable', 503);
|
|
127
|
+
if (start) {
|
|
128
|
+
const callbacks = new URL(authorize).searchParams.getAll('redirect_uri');
|
|
129
|
+
if (callbacks.length !== 1 || callbacks[0] !== start.redirectUri)
|
|
130
|
+
return problem('method_unavailable', 503);
|
|
131
|
+
}
|
|
132
|
+
const expires = Math.floor(Date.now() / 1000) + FLOW_AGE;
|
|
133
|
+
const path = encodeURIComponent(next.slice(1)).replaceAll('.', '%2E');
|
|
134
|
+
return reply({ authorize }, 200, [[flowName, [state, expires, path].join('.'), FLOW_AGE]]);
|
|
135
|
+
}
|
|
136
|
+
function issue(request) {
|
|
137
|
+
return async (session) => {
|
|
138
|
+
const cookies = options.session
|
|
139
|
+
? await options.session.issue(session, request)
|
|
140
|
+
: sessionCookie(session);
|
|
141
|
+
if (!cookies?.length)
|
|
142
|
+
return;
|
|
143
|
+
for (const [name, value, age] of cookies) {
|
|
144
|
+
if (cookieName(name) === flowName || !token(value) || !Number.isSafeInteger(age) || age < 1)
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
return cookies;
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
function sessionCookie(session) {
|
|
151
|
+
const expires = typeof session.expiresAt === 'string' ? Date.parse(session.expiresAt) : NaN;
|
|
152
|
+
const age = Math.floor((expires - Date.now()) / 1000);
|
|
153
|
+
return Number.isFinite(age) && age >= 1 ? [[sessionName, session.token, age]] : undefined;
|
|
154
|
+
}
|
|
155
|
+
async function logout(request, identity) {
|
|
156
|
+
if (options.session) {
|
|
157
|
+
const res = await options.session.logout(request);
|
|
158
|
+
const out = new Headers(res.headers);
|
|
159
|
+
if (res.ok)
|
|
160
|
+
out.append('Set-Cookie', headers([clearFlow]).getSetCookie()[0]);
|
|
161
|
+
return new Response(res.body, { status: res.status, headers: out });
|
|
162
|
+
}
|
|
163
|
+
const credential = readCookie(request, sessionName);
|
|
164
|
+
if (token(credential)) {
|
|
165
|
+
const res = await identity('/v1/client/sign-out', { method: 'POST', bearer: credential });
|
|
166
|
+
discard(res);
|
|
167
|
+
if (res.status !== 204)
|
|
168
|
+
return problem('unavailable', 503);
|
|
169
|
+
}
|
|
170
|
+
return new Response(null, { status: 204, headers: headers([clearFlow, [sessionName, '', 0]]) });
|
|
171
|
+
}
|
|
172
|
+
function readFlow(request) {
|
|
173
|
+
const parts = readCookie(request, flowName)?.split('.');
|
|
174
|
+
if (parts?.length !== 3)
|
|
175
|
+
return;
|
|
176
|
+
const [state, deadline, path] = parts;
|
|
177
|
+
const now = Math.floor(Date.now() / 1000);
|
|
178
|
+
if (!state ||
|
|
179
|
+
!RANDOM.test(state) ||
|
|
180
|
+
!deadline ||
|
|
181
|
+
!/^\d{10}$/.test(deadline) ||
|
|
182
|
+
Number(deadline) <= now ||
|
|
183
|
+
Number(deadline) > now + FLOW_AGE)
|
|
184
|
+
return;
|
|
185
|
+
try {
|
|
186
|
+
return { state, next: nextPath(`/${decodeURIComponent(path ?? '')}`) };
|
|
187
|
+
}
|
|
188
|
+
catch {
|
|
189
|
+
return undefined;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
async function complete(request, url, identity) {
|
|
193
|
+
const flow = readFlow(request);
|
|
194
|
+
const fail = (error = 'signin') => redirect(`${loginPath}?${new URLSearchParams({ error, next: flow?.next ?? fallback })}`, [
|
|
195
|
+
clearFlow,
|
|
196
|
+
]);
|
|
197
|
+
const returned = url.searchParams.getAll('flow');
|
|
198
|
+
const state = returned[0];
|
|
199
|
+
if (!flow ||
|
|
200
|
+
returned.length !== 1 ||
|
|
201
|
+
!state ||
|
|
202
|
+
!RANDOM.test(state) ||
|
|
203
|
+
!sameState(flow.state, state))
|
|
204
|
+
return fail();
|
|
205
|
+
const error = url.searchParams.get('auth_error');
|
|
206
|
+
if (error)
|
|
207
|
+
return fail(error === 'access_denied'
|
|
208
|
+
? 'cancelled'
|
|
209
|
+
: ['unverified_email', 'account_exists'].includes(error)
|
|
210
|
+
? 'use_existing'
|
|
211
|
+
: 'signin');
|
|
212
|
+
const tickets = url.searchParams.getAll('auth_ticket');
|
|
213
|
+
const ticket = tickets[0];
|
|
214
|
+
if (tickets.length !== 1 || !token(ticket))
|
|
215
|
+
return fail();
|
|
216
|
+
try {
|
|
217
|
+
const res = await identity('/v1/client/tickets:redeem', { query: instance, body: { ticket } });
|
|
218
|
+
const data = await json(res);
|
|
219
|
+
const session = obj(data.session);
|
|
220
|
+
if (!res.ok || !token(session.token))
|
|
221
|
+
return fail();
|
|
222
|
+
if (obj(data.user).email_verified !== true)
|
|
223
|
+
return fail('use_existing');
|
|
224
|
+
const cookies = await issue(request)({ token: session.token, expiresAt: session.expires_at });
|
|
225
|
+
return cookies ? redirect(flow.next, [clearFlow, ...cookies]) : fail();
|
|
226
|
+
}
|
|
227
|
+
catch {
|
|
228
|
+
return fail();
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
return async (request) => {
|
|
232
|
+
const url = new URL(request.url);
|
|
233
|
+
if (!(options.isPublicRequest?.(request) ?? url.origin === origin))
|
|
234
|
+
return problem('not_allowed', 403);
|
|
235
|
+
const { pathname } = url;
|
|
236
|
+
const identity = transport(request, fetchUpstream, api);
|
|
237
|
+
if (pathname === CALLBACK)
|
|
238
|
+
return request.method === 'GET' ? complete(request, url, identity) : problem('not_found', 404);
|
|
239
|
+
const legacy = options.legacyStart && pathname === '/auth/start';
|
|
240
|
+
if (!legacy &&
|
|
241
|
+
!['/auth/config', '/auth/email', '/auth/logout'].includes(pathname) &&
|
|
242
|
+
!pathname.startsWith(START))
|
|
243
|
+
return problem('not_found', 404);
|
|
244
|
+
const method = pathname === '/auth/config' ? 'GET' : 'POST';
|
|
245
|
+
const requestOrigin = request.headers.get('origin');
|
|
246
|
+
const site = request.headers.get('sec-fetch-site');
|
|
247
|
+
if (request.method !== method ||
|
|
248
|
+
(site && site !== 'same-origin') ||
|
|
249
|
+
(method === 'POST' ? requestOrigin !== origin : requestOrigin && requestOrigin !== origin))
|
|
250
|
+
return problem('not_allowed', 403);
|
|
251
|
+
try {
|
|
252
|
+
if (pathname === '/auth/config')
|
|
253
|
+
return reply((await discover(identity)).config);
|
|
254
|
+
if (pathname === '/auth/logout')
|
|
255
|
+
return await logout(request, identity);
|
|
256
|
+
if (!/^application\/json(?:\s*;.*)?$/i.test(request.headers.get('content-type') ?? ''))
|
|
257
|
+
return problem('invalid_input', 415);
|
|
258
|
+
let input;
|
|
259
|
+
try {
|
|
260
|
+
input = await jsonBody(request);
|
|
261
|
+
}
|
|
262
|
+
catch {
|
|
263
|
+
return problem('invalid_input', 400);
|
|
264
|
+
}
|
|
265
|
+
const next = nextPath(field(input, 'next', 1024));
|
|
266
|
+
if (pathname.startsWith(START))
|
|
267
|
+
return await start(identity, pathname.slice(START.length), next);
|
|
268
|
+
if (legacy && input.action === 'social')
|
|
269
|
+
return await start(identity, input.provider, next);
|
|
270
|
+
return await emailEntry(identity, input, next, {
|
|
271
|
+
origin,
|
|
272
|
+
loginPath,
|
|
273
|
+
instance,
|
|
274
|
+
session: issue(request),
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
catch {
|
|
278
|
+
return problem('unavailable', 503);
|
|
279
|
+
}
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
function sameState(a, b) {
|
|
283
|
+
let difference = 0;
|
|
284
|
+
for (let i = 0; i < 43; i++)
|
|
285
|
+
difference |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
286
|
+
return difference === 0;
|
|
287
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type AuthCookie, type AuthFetch } from './http.js';
|
|
2
|
+
/** Exchange a verified Identity session via the canonical Management OAuth bridge. */
|
|
3
|
+
export declare function exchangeManagementSession(options: {
|
|
4
|
+
request: Request;
|
|
5
|
+
apiOrigin: string;
|
|
6
|
+
clientId: string;
|
|
7
|
+
redirectUri: string;
|
|
8
|
+
session: string;
|
|
9
|
+
sessionCookie: string;
|
|
10
|
+
refreshCookie: string;
|
|
11
|
+
fetch?: AuthFetch;
|
|
12
|
+
}): Promise<AuthCookie[] | undefined>;
|
package/dist/session.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { json, pkceChallenge, random, token, transport, } from './http.js';
|
|
2
|
+
/** Exchange a verified Identity session via the canonical Management OAuth bridge. */
|
|
3
|
+
export async function exchangeManagementSession(options) {
|
|
4
|
+
const { request, apiOrigin, clientId, redirectUri, session, sessionCookie, refreshCookie } = options;
|
|
5
|
+
const identity = transport(request, options.fetch ?? ((url, init) => fetch(url, init)), apiOrigin);
|
|
6
|
+
const verifier = random();
|
|
7
|
+
const state = random();
|
|
8
|
+
const authorize = await identity('/v1/oauth/authorize', {
|
|
9
|
+
bearer: session,
|
|
10
|
+
body: {
|
|
11
|
+
client_id: clientId,
|
|
12
|
+
redirect_uri: redirectUri,
|
|
13
|
+
response_type: 'code',
|
|
14
|
+
scope: 'openid profile email',
|
|
15
|
+
state,
|
|
16
|
+
nonce: random(),
|
|
17
|
+
code_challenge: await pkceChallenge(verifier),
|
|
18
|
+
code_challenge_method: 'S256',
|
|
19
|
+
},
|
|
20
|
+
});
|
|
21
|
+
const grant = await json(authorize);
|
|
22
|
+
if (!authorize.ok ||
|
|
23
|
+
grant.state !== state ||
|
|
24
|
+
grant.consent_required !== false ||
|
|
25
|
+
!token(grant.code))
|
|
26
|
+
return;
|
|
27
|
+
const exchange = await identity('/v1/oauth/token', {
|
|
28
|
+
body: new URLSearchParams({
|
|
29
|
+
grant_type: 'authorization_code',
|
|
30
|
+
client_id: clientId,
|
|
31
|
+
redirect_uri: redirectUri,
|
|
32
|
+
code: grant.code,
|
|
33
|
+
code_verifier: verifier,
|
|
34
|
+
}),
|
|
35
|
+
});
|
|
36
|
+
const proof = await json(exchange);
|
|
37
|
+
if (!exchange.ok || proof.token_type !== 'Bearer' || !token(proof.access_token))
|
|
38
|
+
return;
|
|
39
|
+
const management = await identity('/v1/auth/identity-exchange', {
|
|
40
|
+
body: { identity_access_token: proof.access_token, client_id: clientId },
|
|
41
|
+
});
|
|
42
|
+
const data = await json(management);
|
|
43
|
+
const { access_token: access, refresh_token: refresh, expires_in: accessAge, refresh_expires_at: expiry, } = data;
|
|
44
|
+
const refreshAge = typeof expiry === 'string' ? Math.floor((Date.parse(expiry) - Date.now()) / 1000) : NaN;
|
|
45
|
+
if (!management.ok ||
|
|
46
|
+
data.token_type !== 'Bearer' ||
|
|
47
|
+
!token(access) ||
|
|
48
|
+
!token(refresh) ||
|
|
49
|
+
typeof accessAge !== 'number' ||
|
|
50
|
+
!Number.isSafeInteger(accessAge) ||
|
|
51
|
+
accessAge < 1 ||
|
|
52
|
+
!Number.isFinite(refreshAge) ||
|
|
53
|
+
refreshAge < 1)
|
|
54
|
+
return;
|
|
55
|
+
return [
|
|
56
|
+
[sessionCookie, access, Math.min(3600, accessAge)],
|
|
57
|
+
[refreshCookie, refresh, Math.min(30 * 86400, refreshAge)],
|
|
58
|
+
];
|
|
59
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,45 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@sylphx/auth",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Web-standard first-party Auth handler and its browser contract",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": {
|
|
8
|
+
"types": "./dist/server.d.ts",
|
|
9
|
+
"default": "./dist/server.js"
|
|
10
|
+
},
|
|
11
|
+
"./client": {
|
|
12
|
+
"types": "./dist/client.d.ts",
|
|
13
|
+
"default": "./dist/client.js"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"scripts": {
|
|
17
|
+
"lint": "biome check .",
|
|
18
|
+
"typecheck": "tsc --noEmit",
|
|
19
|
+
"test": "bun test",
|
|
20
|
+
"build": "tsc -p tsconfig.build.json"
|
|
21
|
+
},
|
|
22
|
+
"devDependencies": {
|
|
23
|
+
"@types/bun": "1.4.0",
|
|
24
|
+
"typescript": "6.0.2"
|
|
25
|
+
},
|
|
26
|
+
"license": "MIT",
|
|
27
|
+
"repository": {
|
|
28
|
+
"type": "git",
|
|
29
|
+
"url": "git+https://github.com/SylphxAI/sylphx-clients.git",
|
|
30
|
+
"directory": "auth"
|
|
31
|
+
},
|
|
32
|
+
"engines": {
|
|
33
|
+
"node": ">=22.12"
|
|
34
|
+
},
|
|
35
|
+
"files": [
|
|
36
|
+
"dist",
|
|
37
|
+
"README.md",
|
|
38
|
+
"LICENSE"
|
|
39
|
+
],
|
|
40
|
+
"publishConfig": {
|
|
41
|
+
"access": "public",
|
|
42
|
+
"tag": "next",
|
|
43
|
+
"provenance": true
|
|
44
|
+
}
|
|
45
|
+
}
|