@sylphx/auth 0.1.1 → 0.1.2
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 +52 -0
- package/dist/client.d.ts +3 -0
- package/dist/discovery.d.ts +45 -0
- package/dist/discovery.js +54 -0
- package/dist/email.d.ts +6 -2
- package/dist/email.js +7 -5
- package/dist/enrollment.d.ts +2 -0
- package/dist/enrollment.js +62 -0
- package/dist/server.d.ts +33 -8
- package/dist/server.js +180 -64
- package/dist/session-cookie.d.ts +10 -0
- package/dist/session-cookie.js +18 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -99,3 +99,55 @@ server loader and pass its JSON as the widget's `initialConfig`. Use
|
|
|
99
99
|
`allowPasswordRegistration: false` to hide and refuse new password signup via
|
|
100
100
|
this handler; password sign-in, confirmation of prior registrations, OTP and
|
|
101
101
|
OAuth remain available according to the instance's capabilities.
|
|
102
|
+
|
|
103
|
+
## Instance keys and entry policy
|
|
104
|
+
|
|
105
|
+
Pass `publishableKey: env.SYLPHX_PUBLISHABLE_KEY` instead of `instance` to
|
|
106
|
+
resolve the tenant via its Access publishable key. The handler uses the bearer
|
|
107
|
+
header on Identity client calls, never the public config response, browser
|
|
108
|
+
URL, or tenant portal. You can provide both to additionally pin the resolved
|
|
109
|
+
ID, slug and environment. Confidential ticket redemption still uses only the
|
|
110
|
+
server key.
|
|
111
|
+
|
|
112
|
+
Set `allowedMethods: ['oauth', 'otp', 'passkey']`, for example, to suppress and
|
|
113
|
+
reject password sign-in, password MFA, registration, and recovery. An empty
|
|
114
|
+
array denies all sign-in methods. The allowlist is local to this handler.
|
|
115
|
+
|
|
116
|
+
An unverified password sign-in is denied by default. To continue a legacy mail
|
|
117
|
+
proof flow, use `issueUnverifiedPassword` to return a short-lived, proof-only
|
|
118
|
+
cookie. Never grant normal application permissions based on this callback;
|
|
119
|
+
verify the mailed proof against the same principal before upgrading the
|
|
120
|
+
session. The normal `session.issue` callback is never invoked in this case.
|
|
121
|
+
|
|
122
|
+
## App session integration
|
|
123
|
+
|
|
124
|
+
- `session.issue` also receives `method`, `provider` (OAuth only), and normalized
|
|
125
|
+
`returnTo`. Optional `signUpSignal(context, request)` emits only the fixed
|
|
126
|
+
`X-Sylphx-Auth-Event: sign_up` response header, and only on confirmed new-user
|
|
127
|
+
sign-in with no GPC header. Return true only after checking affirmative,
|
|
128
|
+
current consent. It emits no user or session identifiers, and never changes
|
|
129
|
+
the HttpOnly session headers. Redirect response headers are not exposed to
|
|
130
|
+
browser JS; consume the marker server-side for OAuth.
|
|
131
|
+
- `readAuthSessionCookie(request, { sessionCookie, legacyCookies })` reads
|
|
132
|
+
the preferred credential for your app's auth middleware. A canonical cookie
|
|
133
|
+
takes precedence; malformed or duplicate candidates do not cause fallback.
|
|
134
|
+
Validate the credential with its authoritative issuer before authorizing
|
|
135
|
+
requests or migrating it. Your middleware can then rotate it into the
|
|
136
|
+
canonical cookie without extending its lifetime. The default logout route
|
|
137
|
+
revokes the presented Identity session and clears the configured names;
|
|
138
|
+
a custom adapter owns revocation and cleanup of its own cookies.
|
|
139
|
+
- `passkeyEnrollment: true` enables POST `/auth/passkey/enroll` using the
|
|
140
|
+
canonical or configured legacy Identity session cookie. Hosts with their own
|
|
141
|
+
session store can provide an async resolver for an Identity credential after
|
|
142
|
+
authenticating the app session. Identity checks the tenant, verified email,
|
|
143
|
+
recent session and WebAuthn proof. Use `SylphxPasskeyEnroll` in a signed-in view.
|
|
144
|
+
- `recoverPassword({ email, returnTo }, request)` enables the recovery-start
|
|
145
|
+
action. Handle the send without disclosing account existence, enforce rate
|
|
146
|
+
limits, and validate the mailed proof in your reset page. Identity's recovery
|
|
147
|
+
operations require their own authorization; this hook does not proxy them
|
|
148
|
+
using a publishable key or issue a session.
|
|
149
|
+
- `directOAuth: true` enables GET `/auth/:provider?returnTo=/account` from a
|
|
150
|
+
same-origin top-level browser navigation. External requests, background
|
|
151
|
+
fetches and requests without browser navigation headers cannot start it.
|
|
152
|
+
Apps using server-side clickwrap must use POST `/auth/start/:provider` to
|
|
153
|
+
bind acceptance to the OAuth flow.
|
package/dist/client.d.ts
CHANGED
|
@@ -6,12 +6,15 @@ export declare const providers: {
|
|
|
6
6
|
readonly microsoft: readonly ["Microsoft", "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"];
|
|
7
7
|
};
|
|
8
8
|
export type Provider = keyof typeof providers;
|
|
9
|
+
export type AuthMethod = 'oauth' | 'password' | 'otp' | 'passkey';
|
|
9
10
|
export type EntryConfig = {
|
|
10
11
|
providers: Provider[];
|
|
11
12
|
password: boolean;
|
|
12
13
|
signup: boolean;
|
|
13
14
|
otp: boolean;
|
|
14
15
|
passkey: boolean;
|
|
16
|
+
recovery?: boolean;
|
|
17
|
+
passkeyEnrollment?: boolean;
|
|
15
18
|
};
|
|
16
19
|
export declare function isProvider(id: unknown): id is Provider;
|
|
17
20
|
export declare function providerDestination(id: Provider, location: unknown): string | undefined;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { AuthMethod, EntryConfig, Provider } from './client.js';
|
|
2
|
+
import { type Data, type Identity } from './http.js';
|
|
3
|
+
export type AuthInstance = {
|
|
4
|
+
slug: string;
|
|
5
|
+
id: string;
|
|
6
|
+
environment: string;
|
|
7
|
+
};
|
|
8
|
+
export type InstanceBinding = {
|
|
9
|
+
instance: AuthInstance;
|
|
10
|
+
publishableKey?: string;
|
|
11
|
+
} | {
|
|
12
|
+
instance?: undefined;
|
|
13
|
+
publishableKey: string;
|
|
14
|
+
};
|
|
15
|
+
export declare function bindInstance({ instance, publishableKey }: InstanceBinding): {
|
|
16
|
+
scope: {
|
|
17
|
+
bearer: string;
|
|
18
|
+
query?: never;
|
|
19
|
+
} | {
|
|
20
|
+
query: {
|
|
21
|
+
instance: string;
|
|
22
|
+
};
|
|
23
|
+
bearer?: never;
|
|
24
|
+
};
|
|
25
|
+
discover(identity: Identity): Promise<{
|
|
26
|
+
data: Data;
|
|
27
|
+
instance: {
|
|
28
|
+
id: string;
|
|
29
|
+
slug: string;
|
|
30
|
+
environment: string;
|
|
31
|
+
};
|
|
32
|
+
}>;
|
|
33
|
+
};
|
|
34
|
+
export declare function entryConfig(methods: Data, providers: Provider[], allows: (method: AuthMethod) => boolean, registration: boolean): EntryConfig;
|
|
35
|
+
export declare const emailMethods: {
|
|
36
|
+
readonly password: "password";
|
|
37
|
+
readonly verify_signup: "password";
|
|
38
|
+
readonly signup: "password";
|
|
39
|
+
readonly mfa: "password";
|
|
40
|
+
readonly otp_start: "otp";
|
|
41
|
+
readonly otp_verify: "otp";
|
|
42
|
+
readonly passkey_start: "passkey";
|
|
43
|
+
readonly passkey_verify: "passkey";
|
|
44
|
+
readonly recovery_start: "password";
|
|
45
|
+
};
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { json, obj, token } from './http.js';
|
|
2
|
+
const SLUG = /^[a-z0-9][a-z0-9-]{0,62}$/;
|
|
3
|
+
export function bindInstance({ instance, publishableKey }) {
|
|
4
|
+
if (instance &&
|
|
5
|
+
(!SLUG.test(instance.slug) || !token(instance.id) || !token(instance.environment)))
|
|
6
|
+
throw new TypeError('Expected an Auth instance');
|
|
7
|
+
if (publishableKey !== undefined &&
|
|
8
|
+
(!token(publishableKey) || !publishableKey.startsWith('sylphx_pk_')))
|
|
9
|
+
throw new TypeError('Expected an Identity publishable key');
|
|
10
|
+
if (!instance && !publishableKey)
|
|
11
|
+
throw new TypeError('Expected an Auth instance or publishable key');
|
|
12
|
+
// Identity accepts the Access publishable key as Authorization: Bearer.
|
|
13
|
+
const scope = publishableKey
|
|
14
|
+
? { bearer: publishableKey }
|
|
15
|
+
: { query: { instance: instance.slug } };
|
|
16
|
+
return {
|
|
17
|
+
scope,
|
|
18
|
+
async discover(identity) {
|
|
19
|
+
const res = await identity('/v1/client/config', scope);
|
|
20
|
+
const data = await json(res);
|
|
21
|
+
const { id, slug, environment } = obj(data.instance);
|
|
22
|
+
if (!res.ok ||
|
|
23
|
+
!token(id) ||
|
|
24
|
+
typeof slug !== 'string' ||
|
|
25
|
+
!SLUG.test(slug) ||
|
|
26
|
+
!token(environment) ||
|
|
27
|
+
(instance &&
|
|
28
|
+
(id !== instance.id || slug !== instance.slug || environment !== instance.environment)))
|
|
29
|
+
throw new Error('Unexpected authentication instance');
|
|
30
|
+
return { data, instance: { id, slug, environment } };
|
|
31
|
+
},
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
export function entryConfig(methods, providers, allows, registration) {
|
|
35
|
+
const password = allows('password') && methods.password === true;
|
|
36
|
+
return {
|
|
37
|
+
providers,
|
|
38
|
+
password,
|
|
39
|
+
signup: password && registration && methods.sign_up === true,
|
|
40
|
+
otp: allows('otp') && methods.email_otp === true,
|
|
41
|
+
passkey: allows('passkey') && methods.passkey === true,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
export const emailMethods = {
|
|
45
|
+
password: 'password',
|
|
46
|
+
verify_signup: 'password',
|
|
47
|
+
signup: 'password',
|
|
48
|
+
mfa: 'password',
|
|
49
|
+
otp_start: 'otp',
|
|
50
|
+
otp_verify: 'otp',
|
|
51
|
+
passkey_start: 'passkey',
|
|
52
|
+
passkey_verify: 'passkey',
|
|
53
|
+
recovery_start: 'password',
|
|
54
|
+
};
|
package/dist/email.d.ts
CHANGED
|
@@ -1,11 +1,15 @@
|
|
|
1
|
+
import type { AuthMethod } from './client.js';
|
|
1
2
|
import { type Data, type Identity } from './http.js';
|
|
2
3
|
export declare function refused(res: Response, error: string): Response;
|
|
3
4
|
export declare function emailEntry(identity: Identity, input: Data, next: string, ctx: {
|
|
4
5
|
origin: string;
|
|
5
6
|
loginPath: string;
|
|
6
|
-
|
|
7
|
+
scope: {
|
|
8
|
+
query?: Record<string, string>;
|
|
9
|
+
bearer?: string;
|
|
10
|
+
};
|
|
7
11
|
mode: 'server' | 'browser';
|
|
8
12
|
allowRegistration: boolean;
|
|
9
13
|
redeem(ticket: string): Promise<Data | undefined>;
|
|
10
|
-
session(data: Data): Promise<Response>;
|
|
14
|
+
session(data: Data, method: Exclude<AuthMethod, 'oauth'>, legacyPassword: boolean): Promise<Response>;
|
|
11
15
|
}): Promise<Response>;
|
package/dist/email.js
CHANGED
|
@@ -8,7 +8,7 @@ export function refused(res, error) {
|
|
|
8
8
|
: problem(error, 400);
|
|
9
9
|
}
|
|
10
10
|
export async function emailEntry(identity, input, next, ctx) {
|
|
11
|
-
const { origin,
|
|
11
|
+
const { origin, scope, session: issue } = ctx;
|
|
12
12
|
const rp = new URL(origin).hostname;
|
|
13
13
|
const action = input.action;
|
|
14
14
|
const email = field(input, 'email', 254)?.trim();
|
|
@@ -43,7 +43,7 @@ export async function emailEntry(identity, input, next, ctx) {
|
|
|
43
43
|
const target = new URL(ctx.loginPath, origin);
|
|
44
44
|
target.searchParams.set('next', next);
|
|
45
45
|
const res = await identity('/v1/client/sign-up', {
|
|
46
|
-
|
|
46
|
+
...scope,
|
|
47
47
|
body: { email, password, redirect_url: target.href },
|
|
48
48
|
});
|
|
49
49
|
const data = await json(res);
|
|
@@ -102,7 +102,7 @@ export async function emailEntry(identity, input, next, ctx) {
|
|
|
102
102
|
default:
|
|
103
103
|
return problem('not_found', 404);
|
|
104
104
|
}
|
|
105
|
-
const res = await identity(path, {
|
|
105
|
+
const res = await identity(path, { ...scope, body });
|
|
106
106
|
const data = await json(res);
|
|
107
107
|
if (res.status === 401 && data.code === 'mfa_required') {
|
|
108
108
|
if ((action === 'password' || action === 'verify_signup') && token(data.mfa_challenge))
|
|
@@ -156,7 +156,9 @@ export async function emailEntry(identity, input, next, ctx) {
|
|
|
156
156
|
return refused(confirmed, 'verification_failed');
|
|
157
157
|
user.email_verified = true;
|
|
158
158
|
}
|
|
159
|
-
|
|
159
|
+
const method = action === 'otp_verify' ? 'otp' : action === 'passkey_verify' ? 'passkey' : 'password';
|
|
160
|
+
const legacyPassword = user.email_verified === false && (action === 'password' || (action === 'mfa' && !verification));
|
|
161
|
+
if (user.email_verified !== true && !legacyPassword)
|
|
160
162
|
return problem('verify_email', 403);
|
|
161
|
-
return issue(result);
|
|
163
|
+
return issue(result, method, legacyPassword);
|
|
162
164
|
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { field, json, obj, problem, reply, token } from './http.js';
|
|
2
|
+
const base64url = /^[A-Za-z0-9_-]+$/;
|
|
3
|
+
export async function enrollPasskey(identity, credential, instanceId, origin, input) {
|
|
4
|
+
if (input.action !== 'begin' && input.action !== 'verify')
|
|
5
|
+
return problem('not_found', 404);
|
|
6
|
+
const rpId = new URL(origin).hostname;
|
|
7
|
+
let body = { rp_id: rpId, origin };
|
|
8
|
+
if (input.action === 'verify') {
|
|
9
|
+
body = {};
|
|
10
|
+
for (const key of ['challenge_id', 'credential_id', 'client_data_json', 'attestation_object']) {
|
|
11
|
+
const value = field(input, key, 16_384);
|
|
12
|
+
if (!value || !base64url.test(value))
|
|
13
|
+
return problem('invalid_input', 400);
|
|
14
|
+
body[key] = value;
|
|
15
|
+
}
|
|
16
|
+
const transports = input.transports ?? [];
|
|
17
|
+
if (!Array.isArray(transports) ||
|
|
18
|
+
transports.length > 16 ||
|
|
19
|
+
!transports.every((value) => typeof value === 'string' && /^[a-z-]{1,32}$/.test(value)))
|
|
20
|
+
return problem('invalid_input', 400);
|
|
21
|
+
body.transports = transports;
|
|
22
|
+
}
|
|
23
|
+
const session = await identity('/v1/client/session', { bearer: credential });
|
|
24
|
+
const current = await json(session);
|
|
25
|
+
if (!session.ok ||
|
|
26
|
+
obj(current.session).instance_id !== instanceId ||
|
|
27
|
+
obj(current.user).email_verified !== true)
|
|
28
|
+
return problem('not_allowed', 403);
|
|
29
|
+
const res = await identity(`/v1/client/me/passkeys/${input.action}`, { bearer: credential, body });
|
|
30
|
+
if (!res.ok) {
|
|
31
|
+
void res.body?.cancel().catch(() => undefined);
|
|
32
|
+
return res.status === 429
|
|
33
|
+
? problem('try_later', 429)
|
|
34
|
+
: problem('method_unavailable', res.status >= 500 ? 503 : 403);
|
|
35
|
+
}
|
|
36
|
+
const data = await json(res);
|
|
37
|
+
if (input.action === 'verify') {
|
|
38
|
+
const passkey = obj(data.passkey);
|
|
39
|
+
return token(passkey.credential_id) && passkey.rp_id === rpId && passkey.origin === origin
|
|
40
|
+
? reply({ enrolled: true })
|
|
41
|
+
: problem('unavailable', 502);
|
|
42
|
+
}
|
|
43
|
+
const { challenge_id, challenge, rp_id, user_id, user_name, public_key_algorithms } = data;
|
|
44
|
+
if (rp_id !== rpId ||
|
|
45
|
+
!token(challenge_id) ||
|
|
46
|
+
!token(challenge) ||
|
|
47
|
+
!token(user_id) ||
|
|
48
|
+
typeof user_name !== 'string' ||
|
|
49
|
+
!user_name ||
|
|
50
|
+
!Array.isArray(public_key_algorithms) ||
|
|
51
|
+
!public_key_algorithms.length ||
|
|
52
|
+
!public_key_algorithms.every(Number.isSafeInteger))
|
|
53
|
+
return problem('unavailable', 502);
|
|
54
|
+
return reply({
|
|
55
|
+
challengeId: challenge_id,
|
|
56
|
+
challenge,
|
|
57
|
+
rpId,
|
|
58
|
+
userId: user_id,
|
|
59
|
+
userName: user_name,
|
|
60
|
+
algorithms: public_key_algorithms,
|
|
61
|
+
});
|
|
62
|
+
}
|
package/dist/server.d.ts
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
import { type AcceptanceVersions, type ClickwrapPolicy } from './acceptance.js';
|
|
2
|
-
import { type Provider } from './client.js';
|
|
2
|
+
import { type AuthMethod, type Provider } from './client.js';
|
|
3
|
+
import { type InstanceBinding } from './discovery.js';
|
|
3
4
|
import { type AuthCookie, type AuthFetch } from './http.js';
|
|
4
5
|
export type { AcceptanceVersions, ClickwrapPolicy } from './acceptance.js';
|
|
6
|
+
export type { AuthMethod } from './client.js';
|
|
5
7
|
export type { AuthCookie, AuthFetch } from './http.js';
|
|
6
8
|
export { jsonBody as readAuthJson } from './http.js';
|
|
7
9
|
export { exchangeManagementSession } from './session.js';
|
|
10
|
+
export { readAuthSessionCookie, type SessionCookieSource } from './session-cookie.js';
|
|
8
11
|
export type IdentitySession = {
|
|
9
12
|
token: string;
|
|
10
13
|
expiresAt: unknown;
|
|
@@ -17,12 +20,23 @@ export type VerifiedIdentity = {
|
|
|
17
20
|
username?: string;
|
|
18
21
|
emailVerified: true;
|
|
19
22
|
};
|
|
20
|
-
export type
|
|
23
|
+
export type AuthIssueContext = {
|
|
24
|
+
method: AuthMethod;
|
|
25
|
+
provider?: Provider;
|
|
26
|
+
returnTo: string;
|
|
27
|
+
};
|
|
28
|
+
export type VerifiedIdentitySession = IdentitySession & AuthIssueContext & {
|
|
21
29
|
sessionId?: string;
|
|
22
30
|
user: VerifiedIdentity;
|
|
23
31
|
isNewUser: boolean;
|
|
24
32
|
acceptance?: AcceptanceVersions;
|
|
25
33
|
};
|
|
34
|
+
export type UnverifiedPasswordSession = Omit<VerifiedIdentitySession, 'user' | 'method'> & {
|
|
35
|
+
method: 'password';
|
|
36
|
+
user: Omit<VerifiedIdentity, 'emailVerified'> & {
|
|
37
|
+
emailVerified: false;
|
|
38
|
+
};
|
|
39
|
+
};
|
|
26
40
|
export type SessionAdapter = {
|
|
27
41
|
issue(session: VerifiedIdentitySession, request: Request): ReturnType<IssueSession>;
|
|
28
42
|
logout(request: Request): Promise<Response>;
|
|
@@ -32,11 +46,22 @@ export type SylphxAuthOptions = {
|
|
|
32
46
|
origin: string;
|
|
33
47
|
/** Trusted Auth API origin. Only the handler sees this value. */
|
|
34
48
|
authApiOrigin: string;
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
49
|
+
allowedMethods?: readonly AuthMethod[];
|
|
50
|
+
/** Separate app-owned handoff for proof-pending sessions; never calls the verified issuer. */
|
|
51
|
+
issueUnverifiedPassword?: (session: UnverifiedPasswordSession, request: Request) => ReturnType<IssueSession>;
|
|
52
|
+
/** Host sends the generic recovery message and owns mailed proof completion. */
|
|
53
|
+
recoverPassword?: (input: {
|
|
54
|
+
email: string;
|
|
55
|
+
returnTo: string;
|
|
56
|
+
}, request: Request) => Promise<void>;
|
|
57
|
+
/** Opt in to same-origin top-level GET /<provider>; clickwrap deployments use POST. */
|
|
58
|
+
directOAuth?: boolean;
|
|
59
|
+
/** Non-sensitive marker emitted only for a new user after host consent and absent GPC. */
|
|
60
|
+
signUpSignal?: (context: Readonly<AuthIssueContext>, request: Request) => boolean | Promise<boolean>;
|
|
61
|
+
/** Fallback names when the canonical cookie is absent; issuer must still authenticate it. */
|
|
62
|
+
legacyCookies?: readonly string[];
|
|
63
|
+
/** Resolve an Identity session token from an authenticated app session for enrollment. */
|
|
64
|
+
passkeyEnrollment?: true | ((request: Request) => Promise<string | undefined>);
|
|
40
65
|
/** Pin the origin of the tenant's verified Account Portal for BYO OAuth. Auth discovers its mount path. */
|
|
41
66
|
tenantAuthOrigin?: string;
|
|
42
67
|
providers?: readonly Provider[];
|
|
@@ -58,7 +83,7 @@ export type SylphxAuthOptions = {
|
|
|
58
83
|
/** Only for hosts with an existing authoritative session and revocation mechanism. */
|
|
59
84
|
session?: SessionAdapter;
|
|
60
85
|
fetch?: AuthFetch;
|
|
61
|
-
} & ({
|
|
86
|
+
} & InstanceBinding & ({
|
|
62
87
|
sessionMode?: 'browser';
|
|
63
88
|
sessionSecret?: never;
|
|
64
89
|
} | {
|
package/dist/server.js
CHANGED
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
import { acceptanceSigner, decodeAcceptance, encodeAcceptance, readAcceptance, } from './acceptance.js';
|
|
2
2
|
import { authRoutePrefix, isProvider, providerDestination, providers, safeReturnTo, } from './client.js';
|
|
3
|
+
import { bindInstance, emailMethods, entryConfig } from './discovery.js';
|
|
3
4
|
import { emailEntry } from './email.js';
|
|
5
|
+
import { enrollPasskey } from './enrollment.js';
|
|
4
6
|
import { cookieName, discard, field, headers, json, jsonBody, obj, problem, RANDOM, random, readCookie, redirect, reply, token, transport, } from './http.js';
|
|
7
|
+
import { readAuthSessionCookie } from './session-cookie.js';
|
|
5
8
|
export { jsonBody as readAuthJson } from './http.js';
|
|
6
9
|
export { exchangeManagementSession } from './session.js';
|
|
10
|
+
export { readAuthSessionCookie } from './session-cookie.js';
|
|
7
11
|
const FLOW_AGE = 600;
|
|
8
12
|
function secureUrl(value) {
|
|
9
13
|
if (typeof value !== 'string')
|
|
@@ -48,15 +52,15 @@ export function createSylphxAuthHandler(options) {
|
|
|
48
52
|
const tenantAuthOrigin = options.tenantAuthOrigin === undefined ? undefined : requireOrigin(options.tenantAuthOrigin);
|
|
49
53
|
if (tenantAuthOrigin && tenantAuthOrigin === api)
|
|
50
54
|
throw new TypeError('Use the tenant Auth origin, not the Auth API origin');
|
|
51
|
-
const
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
const instance = { instance: slug };
|
|
55
|
+
const binding = bindInstance(options);
|
|
56
|
+
const allowed = options.allowedMethods && new Set(options.allowedMethods);
|
|
57
|
+
const allows = (method) => !allowed || allowed.has(method);
|
|
55
58
|
const prefix = authRoutePrefix(options.routePrefix);
|
|
56
59
|
const startRoute = `${prefix}/start`;
|
|
57
60
|
const callbackRoute = `${prefix}/callback`;
|
|
58
61
|
const configRoute = `${prefix}/config`;
|
|
59
62
|
const emailRoute = `${prefix}/email`;
|
|
63
|
+
const enrollmentRoute = `${prefix}/passkey/enroll`;
|
|
60
64
|
const logoutRoute = `${prefix}/logout`;
|
|
61
65
|
const mode = options.sessionMode ?? 'browser';
|
|
62
66
|
const secret = options.sessionSecret;
|
|
@@ -82,13 +86,17 @@ export function createSylphxAuthHandler(options) {
|
|
|
82
86
|
throw new TypeError('Use separate host-only cookie names');
|
|
83
87
|
const clearFlow = [flowName, '', 0];
|
|
84
88
|
const callback = origin + callbackRoute;
|
|
85
|
-
const signable = (value) => JSON.stringify([callback, id, value]);
|
|
89
|
+
const signable = (value) => JSON.stringify([callback, options.instance?.id ?? options.publishableKey, value]);
|
|
90
|
+
const legacyCookies = (options.legacyCookies ?? []).map(cookieName);
|
|
91
|
+
if (new Set([flowName, sessionName, ...legacyCookies]).size !== legacyCookies.length + 2)
|
|
92
|
+
throw new TypeError('Use distinct session and flow cookie names');
|
|
93
|
+
const sessionSource = (request) => readAuthSessionCookie(request, { sessionCookie: sessionName, legacyCookies });
|
|
86
94
|
function accepted(versions, request) {
|
|
87
95
|
return clickwrap ? versions && clickwrap.validate(versions, request) : true;
|
|
88
96
|
}
|
|
89
97
|
async function redeem(identity, ticket) {
|
|
90
98
|
const res = await identity('/v1/client/tickets:redeem', {
|
|
91
|
-
|
|
99
|
+
...binding.scope,
|
|
92
100
|
body: { ticket },
|
|
93
101
|
...(mode === 'server' && secret && { bearer: secret }),
|
|
94
102
|
});
|
|
@@ -101,18 +109,10 @@ export function createSylphxAuthHandler(options) {
|
|
|
101
109
|
const fetchUpstream = options.fetch ?? ((url, init) => fetch(url, init));
|
|
102
110
|
const social = [...new Set(options.providers ?? Object.keys(providers).filter(isProvider))];
|
|
103
111
|
async function discover(identity) {
|
|
104
|
-
const
|
|
105
|
-
const data = await json(res);
|
|
106
|
-
const resolved = obj(data.instance);
|
|
107
|
-
if (!res.ok ||
|
|
108
|
-
resolved.id !== id ||
|
|
109
|
-
resolved.slug !== slug ||
|
|
110
|
-
resolved.environment !== environment)
|
|
111
|
-
throw new Error('Unexpected authentication instance');
|
|
112
|
-
const methods = obj(data.methods);
|
|
112
|
+
const { data, instance } = await binding.discover(identity);
|
|
113
113
|
const redirects = new Map();
|
|
114
114
|
const rows = Array.isArray(data.social) ? data.social.map(obj) : [];
|
|
115
|
-
for (const provider of social) {
|
|
115
|
+
for (const provider of allows('oauth') ? social : []) {
|
|
116
116
|
const entries = rows.filter((row) => row.provider === provider);
|
|
117
117
|
if (entries.length !== 1)
|
|
118
118
|
continue;
|
|
@@ -120,31 +120,32 @@ export function createSylphxAuthHandler(options) {
|
|
|
120
120
|
if (row.credentials === 'shared')
|
|
121
121
|
redirects.set(provider, null);
|
|
122
122
|
else if (row.credentials === 'custom') {
|
|
123
|
-
const start = portalStart(provider, row, data, tenantAuthOrigin, slug);
|
|
123
|
+
const start = portalStart(provider, row, data, tenantAuthOrigin, instance.slug);
|
|
124
124
|
if (start)
|
|
125
125
|
redirects.set(provider, start);
|
|
126
126
|
}
|
|
127
127
|
}
|
|
128
|
-
const config =
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
};
|
|
135
|
-
return { config, redirects };
|
|
128
|
+
const config = entryConfig(obj(data.methods), [...redirects.keys()], allows, allowRegistration);
|
|
129
|
+
if (options.recoverPassword)
|
|
130
|
+
config.recovery = config.password;
|
|
131
|
+
if (options.passkeyEnrollment)
|
|
132
|
+
config.passkeyEnrollment = config.passkey;
|
|
133
|
+
return { config, redirects, instance };
|
|
136
134
|
}
|
|
137
|
-
async function start(identity, provider, next, acceptance) {
|
|
135
|
+
async function start(identity, provider, next, acceptance, navigate = false) {
|
|
138
136
|
if (!isProvider(provider) || !social.includes(provider))
|
|
139
137
|
return problem('unknown_provider', 400);
|
|
140
|
-
|
|
138
|
+
if (!allows('oauth'))
|
|
139
|
+
return problem('method_unavailable', 403);
|
|
140
|
+
const { redirects, instance } = await discover(identity);
|
|
141
141
|
const start = redirects.get(provider);
|
|
142
142
|
if (start === undefined)
|
|
143
143
|
return problem('method_unavailable', 403);
|
|
144
144
|
const state = random();
|
|
145
145
|
const expires = Math.floor(Date.now() / 1000) + FLOW_AGE;
|
|
146
|
-
const
|
|
147
|
-
|
|
146
|
+
const encode = (value) => encodeURIComponent(value).replaceAll('.', '%2E');
|
|
147
|
+
const path = encode(next.slice(1));
|
|
148
|
+
let value = [state, expires, path, provider, encode(instance.id)].join('.');
|
|
148
149
|
if (signer && acceptance) {
|
|
149
150
|
value += `.${encodeAcceptance(acceptance)}`;
|
|
150
151
|
value += `.${await signer.sign(signable(value))}`;
|
|
@@ -156,7 +157,12 @@ export function createSylphxAuthHandler(options) {
|
|
|
156
157
|
// Auth owns upstream PKCE S256, nonce and Apple's form_post. This
|
|
157
158
|
// app's GET callback only receives Auth's one-use sign-in ticket.
|
|
158
159
|
const res = await identity(start?.url ?? `/v1/client/oauth/${provider}/start`, {
|
|
159
|
-
|
|
160
|
+
...(start ? {} : binding.scope),
|
|
161
|
+
query: {
|
|
162
|
+
...(start ? { instance: instance.slug } : binding.scope.query),
|
|
163
|
+
redirect_url: target.href,
|
|
164
|
+
session_mode: mode,
|
|
165
|
+
},
|
|
160
166
|
manual: true,
|
|
161
167
|
});
|
|
162
168
|
const authorize = res.status === 303 && providerDestination(provider, res.headers.get('location'));
|
|
@@ -168,21 +174,34 @@ export function createSylphxAuthHandler(options) {
|
|
|
168
174
|
if (callbacks.length !== 1 || callbacks[0] !== start.redirectUri)
|
|
169
175
|
return problem('method_unavailable', 503);
|
|
170
176
|
}
|
|
171
|
-
|
|
177
|
+
const cookies = [[flowName, value, FLOW_AGE]];
|
|
178
|
+
return navigate ? redirect(authorize, cookies) : reply({ authorize }, 200, cookies);
|
|
172
179
|
}
|
|
173
|
-
function
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
if (!
|
|
180
|
+
function validatedCookies(cookies) {
|
|
181
|
+
if (!cookies?.length)
|
|
182
|
+
return;
|
|
183
|
+
const seen = new Set([flowName]);
|
|
184
|
+
for (const [name, value, age] of cookies) {
|
|
185
|
+
if (seen.has(cookieName(name)) || !token(value) || !Number.isSafeInteger(age) || age < 1)
|
|
179
186
|
return;
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
187
|
+
seen.add(name);
|
|
188
|
+
}
|
|
189
|
+
return cookies;
|
|
190
|
+
}
|
|
191
|
+
async function issue(request, session, context) {
|
|
192
|
+
const cookies = validatedCookies(options.session ? await options.session.issue(session, request) : sessionCookie(session));
|
|
193
|
+
if (!cookies)
|
|
194
|
+
return;
|
|
195
|
+
let signUp = false;
|
|
196
|
+
if (session.isNewUser && !request.headers.has('sec-gpc')) {
|
|
197
|
+
try {
|
|
198
|
+
signUp = (await options.signUpSignal?.(context, request)) === true;
|
|
199
|
+
}
|
|
200
|
+
catch {
|
|
201
|
+
// Optional analytics must not prevent sign-in.
|
|
183
202
|
}
|
|
184
|
-
|
|
185
|
-
};
|
|
203
|
+
}
|
|
204
|
+
return { cookies, signUp };
|
|
186
205
|
}
|
|
187
206
|
function sessionCookie(session) {
|
|
188
207
|
const age = Math.floor(expirySeconds(session.expiresAt) - Date.now() / 1000);
|
|
@@ -196,25 +215,33 @@ export function createSylphxAuthHandler(options) {
|
|
|
196
215
|
out.append('Set-Cookie', headers([clearFlow]).getSetCookie()[0]);
|
|
197
216
|
return new Response(res.body, { status: res.status, headers: out });
|
|
198
217
|
}
|
|
199
|
-
const credential =
|
|
218
|
+
const credential = sessionSource(request)?.value;
|
|
200
219
|
if (token(credential)) {
|
|
201
220
|
const res = await identity('/v1/client/sign-out', { method: 'POST', bearer: credential });
|
|
202
221
|
discard(res);
|
|
203
222
|
if (res.status !== 204)
|
|
204
223
|
return problem('unavailable', 503);
|
|
205
224
|
}
|
|
206
|
-
return new Response(null, {
|
|
225
|
+
return new Response(null, {
|
|
226
|
+
status: 204,
|
|
227
|
+
headers: headers([
|
|
228
|
+
clearFlow,
|
|
229
|
+
...[sessionName, ...legacyCookies].map((name) => [name, '', 0]),
|
|
230
|
+
]),
|
|
231
|
+
});
|
|
207
232
|
}
|
|
208
233
|
async function readFlow(request) {
|
|
209
234
|
const value = readCookie(request, flowName);
|
|
210
235
|
if (!value || (signer && value.length > 3600))
|
|
211
236
|
return;
|
|
212
237
|
const parts = value.split('.');
|
|
213
|
-
if (parts.length !== (signer ?
|
|
238
|
+
if (parts.length !== (signer ? 7 : 5))
|
|
214
239
|
return;
|
|
215
|
-
const [state, deadline, path, encoded, mac] = parts;
|
|
240
|
+
const [state, deadline, path, provider, instanceId, encoded, mac] = parts;
|
|
216
241
|
const now = Math.floor(Date.now() / 1000);
|
|
217
|
-
if (!
|
|
242
|
+
if (!isProvider(provider) ||
|
|
243
|
+
!instanceId ||
|
|
244
|
+
!state ||
|
|
218
245
|
!RANDOM.test(state) ||
|
|
219
246
|
!deadline ||
|
|
220
247
|
!/^\d{10}$/.test(deadline) ||
|
|
@@ -232,7 +259,13 @@ export function createSylphxAuthHandler(options) {
|
|
|
232
259
|
if (!acceptance)
|
|
233
260
|
return;
|
|
234
261
|
}
|
|
235
|
-
return {
|
|
262
|
+
return {
|
|
263
|
+
state,
|
|
264
|
+
provider,
|
|
265
|
+
instanceId: decodeURIComponent(instanceId),
|
|
266
|
+
next: nextPath(`/${decodeURIComponent(path ?? '')}`),
|
|
267
|
+
acceptance,
|
|
268
|
+
};
|
|
236
269
|
}
|
|
237
270
|
catch {
|
|
238
271
|
return undefined;
|
|
@@ -265,18 +298,32 @@ export function createSylphxAuthHandler(options) {
|
|
|
265
298
|
try {
|
|
266
299
|
if ((await accepted(flow.acceptance, request)) !== true)
|
|
267
300
|
return fail('acceptance_required');
|
|
301
|
+
if (!allows('oauth') || !social.includes(flow.provider))
|
|
302
|
+
return fail();
|
|
303
|
+
const pinned = options.publishableKey
|
|
304
|
+
? (await binding.discover(identity)).instance
|
|
305
|
+
: options.instance;
|
|
306
|
+
if (flow.instanceId !== pinned.id)
|
|
307
|
+
return fail();
|
|
268
308
|
const data = await redeem(identity, ticket);
|
|
269
309
|
if (!data)
|
|
270
310
|
return fail();
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
311
|
+
const context = {
|
|
312
|
+
method: 'oauth',
|
|
313
|
+
provider: flow.provider,
|
|
314
|
+
returnTo: flow.next,
|
|
315
|
+
};
|
|
316
|
+
const session = identitySession(data, flow.acceptance, context);
|
|
274
317
|
if (!session)
|
|
275
318
|
return fail();
|
|
319
|
+
if (!session.user.emailVerified)
|
|
320
|
+
return fail('use_existing');
|
|
276
321
|
if ((await accepted(flow.acceptance, request)) !== true)
|
|
277
322
|
return fail('acceptance_required');
|
|
278
|
-
const
|
|
279
|
-
return
|
|
323
|
+
const issued = await issue(request, { ...session, user: { ...session.user, emailVerified: true } }, context);
|
|
324
|
+
return issued
|
|
325
|
+
? signUpHeader(redirect(flow.next, [clearFlow, ...issued.cookies]), issued.signUp)
|
|
326
|
+
: fail();
|
|
280
327
|
}
|
|
281
328
|
catch {
|
|
282
329
|
return fail();
|
|
@@ -290,19 +337,33 @@ export function createSylphxAuthHandler(options) {
|
|
|
290
337
|
const identity = transport(request, fetchUpstream, api);
|
|
291
338
|
if (pathname === callbackRoute)
|
|
292
339
|
return request.method === 'GET' ? complete(request, url, identity) : problem('not_found', 404);
|
|
340
|
+
const direct = options.directOAuth &&
|
|
341
|
+
pathname.startsWith(`${prefix}/`) &&
|
|
342
|
+
isProvider(pathname.slice(prefix.length + 1));
|
|
293
343
|
const legacy = options.legacyStart && pathname === startRoute;
|
|
294
|
-
if (!
|
|
295
|
-
!
|
|
344
|
+
if (!direct &&
|
|
345
|
+
!legacy &&
|
|
346
|
+
![configRoute, emailRoute, logoutRoute, enrollmentRoute].includes(pathname) &&
|
|
296
347
|
!pathname.startsWith(`${startRoute}/`))
|
|
297
348
|
return problem('not_found', 404);
|
|
298
|
-
const method = pathname === configRoute ? 'GET' : 'POST';
|
|
349
|
+
const method = pathname === configRoute || direct ? 'GET' : 'POST';
|
|
299
350
|
const requestOrigin = request.headers.get('origin');
|
|
300
351
|
const site = request.headers.get('sec-fetch-site');
|
|
301
352
|
if (request.method !== method ||
|
|
302
353
|
(site && site !== 'same-origin') ||
|
|
354
|
+
(direct &&
|
|
355
|
+
(site !== 'same-origin' ||
|
|
356
|
+
request.headers.get('sec-fetch-mode') !== 'navigate' ||
|
|
357
|
+
request.headers.get('sec-fetch-dest') !== 'document')) ||
|
|
303
358
|
(method === 'POST' ? requestOrigin !== origin : requestOrigin && requestOrigin !== origin))
|
|
304
359
|
return problem('not_allowed', 403);
|
|
305
360
|
try {
|
|
361
|
+
if (direct) {
|
|
362
|
+
if (clickwrap)
|
|
363
|
+
return problem('acceptance_required', 403);
|
|
364
|
+
const next = nextPath(url.searchParams.get('returnTo') ?? url.searchParams.get('next'));
|
|
365
|
+
return await start(identity, pathname.slice(prefix.length + 1), next, undefined, true);
|
|
366
|
+
}
|
|
306
367
|
if (pathname === configRoute)
|
|
307
368
|
return reply((await discover(identity)).config);
|
|
308
369
|
if (pathname === logoutRoute)
|
|
@@ -316,6 +377,19 @@ export function createSylphxAuthHandler(options) {
|
|
|
316
377
|
catch {
|
|
317
378
|
return problem('invalid_input', 400);
|
|
318
379
|
}
|
|
380
|
+
if (pathname === enrollmentRoute) {
|
|
381
|
+
if (!options.passkeyEnrollment || !allows('passkey'))
|
|
382
|
+
return problem('method_unavailable', 403);
|
|
383
|
+
const credential = options.passkeyEnrollment === true
|
|
384
|
+
? sessionSource(request)?.value
|
|
385
|
+
: await options.passkeyEnrollment(request);
|
|
386
|
+
if (!token(credential))
|
|
387
|
+
return problem('not_allowed', 403);
|
|
388
|
+
const { config, instance } = await discover(identity);
|
|
389
|
+
if (!config.passkey)
|
|
390
|
+
return problem('method_unavailable', 403);
|
|
391
|
+
return await enrollPasskey(identity, credential, instance.id, origin, input);
|
|
392
|
+
}
|
|
319
393
|
const acceptance = clickwrap ? readAcceptance(input.acceptance) : undefined;
|
|
320
394
|
if ((await accepted(acceptance, request)) !== true)
|
|
321
395
|
return problem('acceptance_required', 403);
|
|
@@ -324,19 +398,55 @@ export function createSylphxAuthHandler(options) {
|
|
|
324
398
|
return await start(identity, pathname.slice(startRoute.length + 1), next, acceptance);
|
|
325
399
|
if (legacy && input.action === 'social')
|
|
326
400
|
return await start(identity, input.provider, next, acceptance);
|
|
401
|
+
if (typeof input.action !== 'string' || !Object.hasOwn(emailMethods, input.action))
|
|
402
|
+
return problem('not_found', 404);
|
|
403
|
+
const method = emailMethods[input.action];
|
|
404
|
+
if (!allows(method) || (input.action === 'recovery_start' && !options.recoverPassword))
|
|
405
|
+
return problem('method_unavailable', 403);
|
|
406
|
+
if (allowed ||
|
|
407
|
+
(options.instance && options.publishableKey) ||
|
|
408
|
+
input.action === 'recovery_start') {
|
|
409
|
+
const { config } = await discover(identity);
|
|
410
|
+
if (!config[method] || (input.action === 'signup' && !config.signup))
|
|
411
|
+
return problem('method_unavailable', 403);
|
|
412
|
+
}
|
|
413
|
+
if (input.action === 'recovery_start') {
|
|
414
|
+
if (!options.recoverPassword)
|
|
415
|
+
return problem('method_unavailable', 403);
|
|
416
|
+
const email = field(input, 'email', 254)?.trim();
|
|
417
|
+
if (!email || !/^[^\s@]+@[^\s@]+$/.test(email))
|
|
418
|
+
return problem('invalid_input', 400);
|
|
419
|
+
await options.recoverPassword({ email, returnTo: next }, request);
|
|
420
|
+
return reply({ step: 'recovery_sent' }, 202);
|
|
421
|
+
}
|
|
327
422
|
return await emailEntry(identity, input, next, {
|
|
328
423
|
origin,
|
|
329
424
|
loginPath,
|
|
330
|
-
instance,
|
|
331
425
|
mode,
|
|
332
426
|
allowRegistration,
|
|
427
|
+
scope: binding.scope,
|
|
333
428
|
redeem: (ticket) => redeem(identity, ticket),
|
|
334
|
-
session: async (data) => {
|
|
429
|
+
session: async (data, method, legacyPassword) => {
|
|
335
430
|
if ((await accepted(acceptance, request)) !== true)
|
|
336
431
|
return problem('acceptance_required', 403);
|
|
337
|
-
const
|
|
338
|
-
const
|
|
339
|
-
|
|
432
|
+
const context = { method, returnTo: next };
|
|
433
|
+
const session = identitySession(data, acceptance, context);
|
|
434
|
+
if (!session)
|
|
435
|
+
return problem('session_unavailable', 502);
|
|
436
|
+
if (session.user.emailVerified === false) {
|
|
437
|
+
if (!legacyPassword || !options.issueUnverifiedPassword)
|
|
438
|
+
return problem('verify_email', 403);
|
|
439
|
+
const cookies = validatedCookies(await options.issueUnverifiedPassword({
|
|
440
|
+
...session,
|
|
441
|
+
method: 'password',
|
|
442
|
+
user: { ...session.user, emailVerified: false },
|
|
443
|
+
}, request));
|
|
444
|
+
return cookies ? reply({ next }, 200, cookies) : problem('verify_email', 403);
|
|
445
|
+
}
|
|
446
|
+
const issued = await issue(request, { ...session, user: { ...session.user, emailVerified: true } }, context);
|
|
447
|
+
return issued
|
|
448
|
+
? signUpHeader(reply({ next }, 200, issued.cookies), issued.signUp)
|
|
449
|
+
: problem('session_unavailable', 502);
|
|
340
450
|
},
|
|
341
451
|
});
|
|
342
452
|
}
|
|
@@ -351,18 +461,19 @@ function sameState(a, b) {
|
|
|
351
461
|
difference |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
352
462
|
return difference === 0;
|
|
353
463
|
}
|
|
354
|
-
function
|
|
464
|
+
function identitySession(data, acceptance, context) {
|
|
355
465
|
const session = obj(data.session);
|
|
356
466
|
const user = obj(data.user);
|
|
357
|
-
if (!token(session.token) || !token(user.id) || user.email_verified !==
|
|
467
|
+
if (!token(session.token) || !token(user.id) || typeof user.email_verified !== 'boolean')
|
|
358
468
|
return;
|
|
359
469
|
return {
|
|
470
|
+
...context,
|
|
360
471
|
token: session.token,
|
|
361
472
|
expiresAt: session.expires_at,
|
|
362
473
|
...(token(session.id) && { sessionId: session.id }),
|
|
363
474
|
user: {
|
|
364
475
|
id: user.id,
|
|
365
|
-
emailVerified:
|
|
476
|
+
emailVerified: user.email_verified,
|
|
366
477
|
...(typeof user.email === 'string' && { email: user.email }),
|
|
367
478
|
...(typeof user.name === 'string' && { name: user.name }),
|
|
368
479
|
...(typeof user.username === 'string' && { username: user.username }),
|
|
@@ -371,6 +482,11 @@ function verifiedSession(data, acceptance) {
|
|
|
371
482
|
...(acceptance && { acceptance }),
|
|
372
483
|
};
|
|
373
484
|
}
|
|
485
|
+
function signUpHeader(response, emit) {
|
|
486
|
+
if (emit)
|
|
487
|
+
response.headers.set('X-Sylphx-Auth-Event', 'sign_up');
|
|
488
|
+
return response;
|
|
489
|
+
}
|
|
374
490
|
function expirySeconds(value) {
|
|
375
491
|
if (typeof value === 'number' || (typeof value === 'string' && /^[0-9]+$/.test(value))) {
|
|
376
492
|
const seconds = Number(value);
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export type SessionCookieSource = {
|
|
2
|
+
name: string;
|
|
3
|
+
value: string;
|
|
4
|
+
legacy: boolean;
|
|
5
|
+
};
|
|
6
|
+
/** Read a credential candidate, not an authenticated session. Always validate it with its issuer. */
|
|
7
|
+
export declare function readAuthSessionCookie(request: Request, options?: {
|
|
8
|
+
sessionCookie?: string;
|
|
9
|
+
legacyCookies?: readonly string[];
|
|
10
|
+
}): SessionCookieSource | undefined;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { cookieName, token } from './http.js';
|
|
2
|
+
/** Read a credential candidate, not an authenticated session. Always validate it with its issuer. */
|
|
3
|
+
export function readAuthSessionCookie(request, options = {}) {
|
|
4
|
+
const canonical = cookieName(options.sessionCookie ?? '__Host-auth_session');
|
|
5
|
+
const names = [canonical, ...(options.legacyCookies ?? []).map(cookieName)];
|
|
6
|
+
const parts = (request.headers.get('cookie') ?? '').split(';').map((part) => part.trim());
|
|
7
|
+
for (const name of names) {
|
|
8
|
+
const matches = parts.filter((part) => part.startsWith(`${name}=`));
|
|
9
|
+
if (!matches.length)
|
|
10
|
+
continue;
|
|
11
|
+
const value = matches[0]?.slice(name.length + 1);
|
|
12
|
+
// An invalid or ambiguous higher-priority cookie never falls back.
|
|
13
|
+
return matches.length === 1 && token(value)
|
|
14
|
+
? { name, value, legacy: name !== canonical }
|
|
15
|
+
: undefined;
|
|
16
|
+
}
|
|
17
|
+
return undefined;
|
|
18
|
+
}
|