@sylphx/auth 0.1.0 → 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 CHANGED
@@ -52,3 +52,102 @@ Install this package with your package manager. Use a registry version from the
52
52
  shared clients release, and Node 22.12 or later (or a worker that supplies the
53
53
  standard Fetch and Web Crypto APIs). The existing `@sylphx/sdk` and React imports
54
54
  are unchanged.
55
+
56
+ ## Confidential sign-in and versioned acceptance
57
+
58
+ Set `sessionMode: 'server'` and `sessionSecret` to the instance environment's Access
59
+ secret key with `auth:admin`. The handler requests a one-use ticket for OTP,
60
+ password (including MFA), passkey, and OAuth, then redeems it against the
61
+ configured Auth API. Only redemption receives the secret. The browser gets
62
+ an HttpOnly cookie and a local navigation target, never a bearer or an email
63
+ or passkey ticket in JSON. A failed redemption never falls back to browser
64
+ mode. Omit both options to keep the existing browser-mode upstream contract.
65
+
66
+ The optional `session.issue(session, request)` adapter receives `session.user`
67
+ (verified ID, email status, and profile fields Auth supplied), `sessionId` when
68
+ present, `isNewUser` (false if Auth omits `is_new_user`), and `acceptance` when
69
+ configured. It retains the existing `token` and raw `expiresAt` fields. An adapter
70
+ returns its own cookie tuples and supplies the matching `session.logout` hook.
71
+ The default cookie supports Unix seconds (number or decimal string) and ISO
72
+ timestamps with explicit timezones.
73
+
74
+ For clickwrap, the host shows its own copy and sends an `acceptance` map after
75
+ explicit agreement, e.g. `{ terms: 'v2', privacy: '2026-11-24' }`. Configure
76
+ `clickwrap` on the server to require and validate the map:
77
+
78
+ ```ts
79
+ const clickwrap = {
80
+ signingKey: serverEnv.AUTH_CLICKWRAP_KEY, // independent, random, shared by all app replicas
81
+ validate: (versions: Readonly<Record<string, string>>) =>
82
+ versions.terms === currentTermsVersion && versions.privacy === currentPrivacyVersion,
83
+ }
84
+ ```
85
+
86
+ The validator is a repeatable, read-only policy check, not an audit hook.
87
+ The handler checks consent before starting sign-in and before issuing app
88
+ cookies. For OAuth, the signed flow cookie binds the versions to the callback;
89
+ if policy changed during the redirect, the app asks the user to accept again.
90
+ For OTP, MFA, password, and passkey, include acceptance in each POST. The host
91
+ owns its evidence store and can record the accepted versions for the verified
92
+ principal in `session.issue` before returning cookies. This only gates sessions
93
+ issued through this handler; it does not change Auth instance policy or revoke
94
+ sessions that already exist.
95
+
96
+ Mount under another path with `routePrefix: '/account/auth'` and give the Solid
97
+ widget the same prefix. For SSR, call the handler's GET config route from your
98
+ server loader and pass its JSON as the widget's `initialConfig`. Use
99
+ `allowPasswordRegistration: false` to hide and refuse new password signup via
100
+ this handler; password sign-in, confirmation of prior registrations, OTP and
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.
@@ -0,0 +1,14 @@
1
+ export type AcceptanceVersions = Readonly<Record<string, string>>;
2
+ export type ClickwrapPolicy = {
3
+ /** Shared, high-entropy server-only key (at least 32 UTF-8 bytes). */
4
+ signingKey: string;
5
+ /** Check the submitted versions against current policy. Only true permits sign-in. */
6
+ validate(versions: AcceptanceVersions, request: Request): boolean | Promise<boolean>;
7
+ };
8
+ export declare function readAcceptance(value: unknown): AcceptanceVersions | undefined;
9
+ export declare function acceptanceSigner(secret: string): {
10
+ sign(value: string): Promise<string>;
11
+ verify(value: string, mac: string): Promise<boolean>;
12
+ };
13
+ export declare function encodeAcceptance(versions: AcceptanceVersions): string;
14
+ export declare function decodeAcceptance(value: string): AcceptanceVersions | undefined;
@@ -0,0 +1,48 @@
1
+ import { RANDOM } from './http.js';
2
+ export function readAcceptance(value) {
3
+ if (!value || typeof value !== 'object' || Array.isArray(value))
4
+ return;
5
+ const entries = Object.entries(value);
6
+ if (!entries.length || entries.length > 8)
7
+ return;
8
+ const valid = entries.every(([key, version]) => /^[A-Za-z0-9][A-Za-z0-9_-]{0,31}$/.test(key) &&
9
+ typeof version === 'string' &&
10
+ /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/.test(version));
11
+ return valid ? Object.freeze(Object.assign(Object.create(null), value)) : undefined;
12
+ }
13
+ export function acceptanceSigner(secret) {
14
+ const encoder = new TextEncoder();
15
+ const bytes = encoder.encode(secret);
16
+ if (bytes.byteLength < 32)
17
+ throw new TypeError('Expected a high-entropy clickwrap signing key');
18
+ const key = () => crypto.subtle.importKey('raw', bytes, { name: 'HMAC', hash: 'SHA-256' }, false, [
19
+ 'sign',
20
+ 'verify',
21
+ ]);
22
+ return {
23
+ async sign(value) {
24
+ return encode(new Uint8Array(await crypto.subtle.sign('HMAC', await key(), encoder.encode(value))));
25
+ },
26
+ async verify(value, mac) {
27
+ return (RANDOM.test(mac) &&
28
+ crypto.subtle.verify('HMAC', await key(), decode(mac), encoder.encode(value)));
29
+ },
30
+ };
31
+ }
32
+ function encode(bytes) {
33
+ return btoa(String.fromCharCode(...bytes))
34
+ .replaceAll('+', '-')
35
+ .replaceAll('/', '_')
36
+ .replace(/=+$/, '');
37
+ }
38
+ function decode(value) {
39
+ return Uint8Array.from(atob(value.replaceAll('-', '+').replaceAll('_', '/')), (c) => c.charCodeAt(0));
40
+ }
41
+ export function encodeAcceptance(versions) {
42
+ return encode(new TextEncoder().encode(JSON.stringify(versions)));
43
+ }
44
+ export function decodeAcceptance(value) {
45
+ if (!/^[A-Za-z0-9_-]{1,1100}$/.test(value))
46
+ return;
47
+ return readAcceptance(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(decode(value))));
48
+ }
package/dist/client.d.ts CHANGED
@@ -6,14 +6,19 @@ 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;
18
21
  /** Never return an absolute or protocol-relative URL, even after normalization. */
19
22
  export declare function safeReturnTo(value: unknown, fallback?: string): string;
23
+ /** Resolve the canonical same-origin mount used by the handler and widget. */
24
+ export declare function authRoutePrefix(value?: string): string;
package/dist/client.js CHANGED
@@ -42,3 +42,9 @@ function relativePath(value) {
42
42
  export function safeReturnTo(value, fallback = '/') {
43
43
  return relativePath(value) ?? relativePath(fallback) ?? '/';
44
44
  }
45
+ /** Resolve the canonical same-origin mount used by the handler and widget. */
46
+ export function authRoutePrefix(value = '/auth') {
47
+ if (!/^\/(?:[A-Za-z0-9_-]+\/)*[A-Za-z0-9_-]+$/.test(value))
48
+ throw new TypeError('Expected a canonical Auth route prefix');
49
+ return value;
50
+ }
@@ -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,9 +1,15 @@
1
+ import type { AuthMethod } from './client.js';
1
2
  import { type Data, type Identity } from './http.js';
2
- import type { IssueSession } from './server.js';
3
3
  export declare function refused(res: Response, error: string): Response;
4
4
  export declare function emailEntry(identity: Identity, input: Data, next: string, ctx: {
5
5
  origin: string;
6
6
  loginPath: string;
7
- instance: Record<string, string>;
8
- session: IssueSession;
7
+ scope: {
8
+ query?: Record<string, string>;
9
+ bearer?: string;
10
+ };
11
+ mode: 'server' | 'browser';
12
+ allowRegistration: boolean;
13
+ redeem(ticket: string): Promise<Data | undefined>;
14
+ session(data: Data, method: Exclude<AuthMethod, 'oauth'>, legacyPassword: boolean): Promise<Response>;
9
15
  }): Promise<Response>;
package/dist/email.js CHANGED
@@ -8,14 +8,14 @@ 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, instance, session: issue } = ctx;
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();
15
15
  const password = field(input, 'password', 1024);
16
16
  const code = field(input, 'code', 128);
17
17
  let path;
18
- let body = { session_mode: 'browser' };
18
+ let body = { session_mode: ctx.mode };
19
19
  const challengeId = field(input, 'challengeId', 200);
20
20
  const secret = field(input, 'verification', 256);
21
21
  const verification = token(challengeId) && token(secret)
@@ -33,6 +33,8 @@ export async function emailEntry(identity, input, next, ctx) {
33
33
  break;
34
34
  }
35
35
  case 'signup': {
36
+ if (!ctx.allowRegistration)
37
+ return problem('method_unavailable', 403);
36
38
  if (!email ||
37
39
  !password ||
38
40
  new TextEncoder().encode(password).byteLength < 12 ||
@@ -41,7 +43,7 @@ export async function emailEntry(identity, input, next, ctx) {
41
43
  const target = new URL(ctx.loginPath, origin);
42
44
  target.searchParams.set('next', next);
43
45
  const res = await identity('/v1/client/sign-up', {
44
- query: instance,
46
+ ...scope,
45
47
  body: { email, password, redirect_url: target.href },
46
48
  });
47
49
  const data = await json(res);
@@ -100,7 +102,7 @@ export async function emailEntry(identity, input, next, ctx) {
100
102
  default:
101
103
  return problem('not_found', 404);
102
104
  }
103
- const res = await identity(path, { query: instance, body });
105
+ const res = await identity(path, { ...scope, body });
104
106
  const data = await json(res);
105
107
  if (res.status === 401 && data.code === 'mfa_required') {
106
108
  if ((action === 'password' || action === 'verify_signup') && token(data.mfa_challenge))
@@ -133,9 +135,13 @@ export async function emailEntry(identity, input, next, ctx) {
133
135
  });
134
136
  if (action === 'otp_start' || action === 'passkey_start')
135
137
  return problem('unavailable', 502);
136
- const session = obj(data.session);
138
+ const ticket = data.ticket;
139
+ const result = ctx.mode === 'server' ? token(ticket) && (await ctx.redeem(ticket)) : data;
140
+ if (!result)
141
+ return problem('session_unavailable', 502);
142
+ const session = obj(result.session);
137
143
  const credential = session.token;
138
- const user = obj(data.user);
144
+ const user = obj(result.user);
139
145
  if (!token(credential) || !token(user.id))
140
146
  return problem('unavailable', 502);
141
147
  if (verification && (action === 'verify_signup' || action === 'mfa')) {
@@ -148,9 +154,11 @@ export async function emailEntry(identity, input, next, ctx) {
148
154
  const result = await json(confirmed);
149
155
  if (!confirmed.ok || obj(result.verification).principal_id !== user.id)
150
156
  return refused(confirmed, 'verification_failed');
157
+ user.email_verified = true;
151
158
  }
152
- else if (user.email_verified !== true)
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)
153
162
  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);
163
+ return issue(result, method, legacyPassword);
156
164
  }
@@ -0,0 +1,2 @@
1
+ import { type Data, type Identity } from './http.js';
2
+ export declare function enrollPasskey(identity: Identity, credential: string, instanceId: string, origin: string, input: Data): Promise<Response>;
@@ -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,15 +1,44 @@
1
- import { type Provider } from './client.js';
1
+ import { type AcceptanceVersions, type ClickwrapPolicy } from './acceptance.js';
2
+ import { type AuthMethod, type Provider } from './client.js';
3
+ import { type InstanceBinding } from './discovery.js';
2
4
  import { type AuthCookie, type AuthFetch } from './http.js';
5
+ export type { AcceptanceVersions, ClickwrapPolicy } from './acceptance.js';
6
+ export type { AuthMethod } from './client.js';
3
7
  export type { AuthCookie, AuthFetch } from './http.js';
4
8
  export { jsonBody as readAuthJson } from './http.js';
5
9
  export { exchangeManagementSession } from './session.js';
10
+ export { readAuthSessionCookie, type SessionCookieSource } from './session-cookie.js';
6
11
  export type IdentitySession = {
7
12
  token: string;
8
13
  expiresAt: unknown;
9
14
  };
10
15
  export type IssueSession = (session: IdentitySession) => Promise<readonly AuthCookie[] | undefined>;
11
- type SessionAdapter = {
12
- issue(session: IdentitySession, request: Request): ReturnType<IssueSession>;
16
+ export type VerifiedIdentity = {
17
+ id: string;
18
+ email?: string;
19
+ name?: string;
20
+ username?: string;
21
+ emailVerified: true;
22
+ };
23
+ export type AuthIssueContext = {
24
+ method: AuthMethod;
25
+ provider?: Provider;
26
+ returnTo: string;
27
+ };
28
+ export type VerifiedIdentitySession = IdentitySession & AuthIssueContext & {
29
+ sessionId?: string;
30
+ user: VerifiedIdentity;
31
+ isNewUser: boolean;
32
+ acceptance?: AcceptanceVersions;
33
+ };
34
+ export type UnverifiedPasswordSession = Omit<VerifiedIdentitySession, 'user' | 'method'> & {
35
+ method: 'password';
36
+ user: Omit<VerifiedIdentity, 'emailVerified'> & {
37
+ emailVerified: false;
38
+ };
39
+ };
40
+ export type SessionAdapter = {
41
+ issue(session: VerifiedIdentitySession, request: Request): ReturnType<IssueSession>;
13
42
  logout(request: Request): Promise<Response>;
14
43
  };
15
44
  export type SylphxAuthOptions = {
@@ -17,17 +46,34 @@ export type SylphxAuthOptions = {
17
46
  origin: string;
18
47
  /** Trusted Auth API origin. Only the handler sees this value. */
19
48
  authApiOrigin: string;
20
- instance: {
21
- slug: string;
22
- id: string;
23
- environment: string;
24
- };
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>);
25
65
  /** Pin the origin of the tenant's verified Account Portal for BYO OAuth. Auth discovers its mount path. */
26
66
  tenantAuthOrigin?: string;
27
67
  providers?: readonly Provider[];
28
68
  /** Transitional alias for a preexisting client that posts action and provider to /auth/start. */
29
69
  legacyStart?: boolean;
30
70
  loginPath?: string;
71
+ /** Same-origin mount pathname, e.g. /account/auth. Defaults to /auth. */
72
+ routePrefix?: string;
73
+ /** Disable new password registration, not password sign-in. */
74
+ allowPasswordRegistration?: boolean;
75
+ /** App-owned policy. Ignored unless configured; when configured, fails closed. */
76
+ clickwrap?: ClickwrapPolicy;
31
77
  defaultReturnTo?: string;
32
78
  allowReturnTo?: (path: string) => boolean;
33
79
  flowCookie?: string;
@@ -37,5 +83,11 @@ export type SylphxAuthOptions = {
37
83
  /** Only for hosts with an existing authoritative session and revocation mechanism. */
38
84
  session?: SessionAdapter;
39
85
  fetch?: AuthFetch;
40
- };
86
+ } & InstanceBinding & ({
87
+ sessionMode?: 'browser';
88
+ sessionSecret?: never;
89
+ } | {
90
+ sessionMode: 'server';
91
+ sessionSecret: string;
92
+ });
41
93
  export declare function createSylphxAuthHandler(options: SylphxAuthOptions): (request: Request) => Promise<Response>;
package/dist/server.js CHANGED
@@ -1,11 +1,14 @@
1
- import { isProvider, providerDestination, providers, safeReturnTo, } from './client.js';
1
+ import { acceptanceSigner, decodeAcceptance, encodeAcceptance, readAcceptance, } from './acceptance.js';
2
+ import { authRoutePrefix, isProvider, providerDestination, providers, safeReturnTo, } from './client.js';
3
+ import { bindInstance, emailMethods, entryConfig } from './discovery.js';
2
4
  import { emailEntry } from './email.js';
5
+ import { enrollPasskey } from './enrollment.js';
3
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';
4
8
  export { jsonBody as readAuthJson } from './http.js';
5
9
  export { exchangeManagementSession } from './session.js';
10
+ export { readAuthSessionCookie } from './session-cookie.js';
6
11
  const FLOW_AGE = 600;
7
- const START = '/auth/start/';
8
- const CALLBACK = '/auth/callback';
9
12
  function secureUrl(value) {
10
13
  if (typeof value !== 'string')
11
14
  return;
@@ -49,10 +52,25 @@ export function createSylphxAuthHandler(options) {
49
52
  const tenantAuthOrigin = options.tenantAuthOrigin === undefined ? undefined : requireOrigin(options.tenantAuthOrigin);
50
53
  if (tenantAuthOrigin && tenantAuthOrigin === api)
51
54
  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 };
55
+ const binding = bindInstance(options);
56
+ const allowed = options.allowedMethods && new Set(options.allowedMethods);
57
+ const allows = (method) => !allowed || allowed.has(method);
58
+ const prefix = authRoutePrefix(options.routePrefix);
59
+ const startRoute = `${prefix}/start`;
60
+ const callbackRoute = `${prefix}/callback`;
61
+ const configRoute = `${prefix}/config`;
62
+ const emailRoute = `${prefix}/email`;
63
+ const enrollmentRoute = `${prefix}/passkey/enroll`;
64
+ const logoutRoute = `${prefix}/logout`;
65
+ const mode = options.sessionMode ?? 'browser';
66
+ const secret = options.sessionSecret;
67
+ if (mode === 'server' &&
68
+ (!token(secret) ||
69
+ (!secret.startsWith('sylphx_sk_') && !secret.startsWith('identity_org_key_'))))
70
+ throw new TypeError('Expected an instance secret key for server mode');
71
+ const clickwrap = options.clickwrap;
72
+ const signer = clickwrap && acceptanceSigner(clickwrap.signingKey);
73
+ const allowRegistration = options.allowPasswordRegistration !== false;
56
74
  const loginPath = safeReturnTo(options.loginPath, '/login');
57
75
  if (/[?#]/.test(loginPath))
58
76
  throw new TypeError('Expected a login pathname');
@@ -67,22 +85,34 @@ export function createSylphxAuthHandler(options) {
67
85
  ![flowName, sessionName].every((name) => name.startsWith('__Host-')))
68
86
  throw new TypeError('Use separate host-only cookie names');
69
87
  const clearFlow = [flowName, '', 0];
70
- const callback = origin + CALLBACK;
88
+ const callback = origin + callbackRoute;
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 });
94
+ function accepted(versions, request) {
95
+ return clickwrap ? versions && clickwrap.validate(versions, request) : true;
96
+ }
97
+ async function redeem(identity, ticket) {
98
+ const res = await identity('/v1/client/tickets:redeem', {
99
+ ...binding.scope,
100
+ body: { ticket },
101
+ ...(mode === 'server' && secret && { bearer: secret }),
102
+ });
103
+ if (!res.ok) {
104
+ discard(res);
105
+ return undefined;
106
+ }
107
+ return json(res);
108
+ }
71
109
  const fetchUpstream = options.fetch ?? ((url, init) => fetch(url, init));
72
110
  const social = [...new Set(options.providers ?? Object.keys(providers).filter(isProvider))];
73
111
  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);
112
+ const { data, instance } = await binding.discover(identity);
83
113
  const redirects = new Map();
84
114
  const rows = Array.isArray(data.social) ? data.social.map(obj) : [];
85
- for (const provider of social) {
115
+ for (const provider of allows('oauth') ? social : []) {
86
116
  const entries = rows.filter((row) => row.provider === provider);
87
117
  if (entries.length !== 1)
88
118
  continue;
@@ -90,34 +120,49 @@ export function createSylphxAuthHandler(options) {
90
120
  if (row.credentials === 'shared')
91
121
  redirects.set(provider, null);
92
122
  else if (row.credentials === 'custom') {
93
- const start = portalStart(provider, row, data, tenantAuthOrigin, slug);
123
+ const start = portalStart(provider, row, data, tenantAuthOrigin, instance.slug);
94
124
  if (start)
95
125
  redirects.set(provider, start);
96
126
  }
97
127
  }
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 };
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 };
106
134
  }
107
- async function start(identity, provider, next) {
135
+ async function start(identity, provider, next, acceptance, navigate = false) {
108
136
  if (!isProvider(provider) || !social.includes(provider))
109
137
  return problem('unknown_provider', 400);
110
- const { redirects } = await discover(identity);
138
+ if (!allows('oauth'))
139
+ return problem('method_unavailable', 403);
140
+ const { redirects, instance } = await discover(identity);
111
141
  const start = redirects.get(provider);
112
142
  if (start === undefined)
113
143
  return problem('method_unavailable', 403);
114
144
  const state = random();
145
+ const expires = Math.floor(Date.now() / 1000) + FLOW_AGE;
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('.');
149
+ if (signer && acceptance) {
150
+ value += `.${encodeAcceptance(acceptance)}`;
151
+ value += `.${await signer.sign(signable(value))}`;
152
+ if (value.length > 3600)
153
+ return problem('invalid_input', 400);
154
+ }
115
155
  const target = new URL(callback);
116
156
  target.searchParams.set('flow', state);
117
157
  // Auth owns upstream PKCE S256, nonce and Apple's form_post. This
118
158
  // app's GET callback only receives Auth's one-use sign-in ticket.
119
159
  const res = await identity(start?.url ?? `/v1/client/oauth/${provider}/start`, {
120
- query: { ...instance, redirect_url: target.href, session_mode: 'browser' },
160
+ ...(start ? {} : binding.scope),
161
+ query: {
162
+ ...(start ? { instance: instance.slug } : binding.scope.query),
163
+ redirect_url: target.href,
164
+ session_mode: mode,
165
+ },
121
166
  manual: true,
122
167
  });
123
168
  const authorize = res.status === 303 && providerDestination(provider, res.headers.get('location'));
@@ -129,28 +174,38 @@ export function createSylphxAuthHandler(options) {
129
174
  if (callbacks.length !== 1 || callbacks[0] !== start.redirectUri)
130
175
  return problem('method_unavailable', 503);
131
176
  }
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]]);
177
+ const cookies = [[flowName, value, FLOW_AGE]];
178
+ return navigate ? redirect(authorize, cookies) : reply({ authorize }, 200, cookies);
135
179
  }
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)
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)
142
186
  return;
143
- for (const [name, value, age] of cookies) {
144
- if (cookieName(name) === flowName || !token(value) || !Number.isSafeInteger(age) || age < 1)
145
- return;
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;
146
199
  }
147
- return cookies;
148
- };
200
+ catch {
201
+ // Optional analytics must not prevent sign-in.
202
+ }
203
+ }
204
+ return { cookies, signUp };
149
205
  }
150
206
  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;
207
+ const age = Math.floor(expirySeconds(session.expiresAt) - Date.now() / 1000);
208
+ return Number.isSafeInteger(age) && age >= 1 ? [[sessionName, session.token, age]] : undefined;
154
209
  }
155
210
  async function logout(request, identity) {
156
211
  if (options.session) {
@@ -160,22 +215,33 @@ export function createSylphxAuthHandler(options) {
160
215
  out.append('Set-Cookie', headers([clearFlow]).getSetCookie()[0]);
161
216
  return new Response(res.body, { status: res.status, headers: out });
162
217
  }
163
- const credential = readCookie(request, sessionName);
218
+ const credential = sessionSource(request)?.value;
164
219
  if (token(credential)) {
165
220
  const res = await identity('/v1/client/sign-out', { method: 'POST', bearer: credential });
166
221
  discard(res);
167
222
  if (res.status !== 204)
168
223
  return problem('unavailable', 503);
169
224
  }
170
- return new Response(null, { status: 204, headers: headers([clearFlow, [sessionName, '', 0]]) });
225
+ return new Response(null, {
226
+ status: 204,
227
+ headers: headers([
228
+ clearFlow,
229
+ ...[sessionName, ...legacyCookies].map((name) => [name, '', 0]),
230
+ ]),
231
+ });
171
232
  }
172
- function readFlow(request) {
173
- const parts = readCookie(request, flowName)?.split('.');
174
- if (parts?.length !== 3)
233
+ async function readFlow(request) {
234
+ const value = readCookie(request, flowName);
235
+ if (!value || (signer && value.length > 3600))
236
+ return;
237
+ const parts = value.split('.');
238
+ if (parts.length !== (signer ? 7 : 5))
175
239
  return;
176
- const [state, deadline, path] = parts;
240
+ const [state, deadline, path, provider, instanceId, encoded, mac] = parts;
177
241
  const now = Math.floor(Date.now() / 1000);
178
- if (!state ||
242
+ if (!isProvider(provider) ||
243
+ !instanceId ||
244
+ !state ||
179
245
  !RANDOM.test(state) ||
180
246
  !deadline ||
181
247
  !/^\d{10}$/.test(deadline) ||
@@ -183,14 +249,30 @@ export function createSylphxAuthHandler(options) {
183
249
  Number(deadline) > now + FLOW_AGE)
184
250
  return;
185
251
  try {
186
- return { state, next: nextPath(`/${decodeURIComponent(path ?? '')}`) };
252
+ let acceptance;
253
+ if (signer) {
254
+ if (!encoded ||
255
+ !mac ||
256
+ !(await signer.verify(signable(value.slice(0, -mac.length - 1)), mac)))
257
+ return;
258
+ acceptance = decodeAcceptance(encoded);
259
+ if (!acceptance)
260
+ return;
261
+ }
262
+ return {
263
+ state,
264
+ provider,
265
+ instanceId: decodeURIComponent(instanceId),
266
+ next: nextPath(`/${decodeURIComponent(path ?? '')}`),
267
+ acceptance,
268
+ };
187
269
  }
188
270
  catch {
189
271
  return undefined;
190
272
  }
191
273
  }
192
274
  async function complete(request, url, identity) {
193
- const flow = readFlow(request);
275
+ const flow = await readFlow(request);
194
276
  const fail = (error = 'signin') => redirect(`${loginPath}?${new URLSearchParams({ error, next: flow?.next ?? fallback })}`, [
195
277
  clearFlow,
196
278
  ]);
@@ -214,15 +296,34 @@ export function createSylphxAuthHandler(options) {
214
296
  if (tickets.length !== 1 || !token(ticket))
215
297
  return fail();
216
298
  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))
299
+ if ((await accepted(flow.acceptance, request)) !== true)
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();
308
+ const data = await redeem(identity, ticket);
309
+ if (!data)
221
310
  return fail();
222
- if (obj(data.user).email_verified !== true)
311
+ const context = {
312
+ method: 'oauth',
313
+ provider: flow.provider,
314
+ returnTo: flow.next,
315
+ };
316
+ const session = identitySession(data, flow.acceptance, context);
317
+ if (!session)
318
+ return fail();
319
+ if (!session.user.emailVerified)
223
320
  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();
321
+ if ((await accepted(flow.acceptance, request)) !== true)
322
+ return fail('acceptance_required');
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();
226
327
  }
227
328
  catch {
228
329
  return fail();
@@ -234,24 +335,38 @@ export function createSylphxAuthHandler(options) {
234
335
  return problem('not_allowed', 403);
235
336
  const { pathname } = url;
236
337
  const identity = transport(request, fetchUpstream, api);
237
- if (pathname === CALLBACK)
338
+ if (pathname === callbackRoute)
238
339
  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))
340
+ const direct = options.directOAuth &&
341
+ pathname.startsWith(`${prefix}/`) &&
342
+ isProvider(pathname.slice(prefix.length + 1));
343
+ const legacy = options.legacyStart && pathname === startRoute;
344
+ if (!direct &&
345
+ !legacy &&
346
+ ![configRoute, emailRoute, logoutRoute, enrollmentRoute].includes(pathname) &&
347
+ !pathname.startsWith(`${startRoute}/`))
243
348
  return problem('not_found', 404);
244
- const method = pathname === '/auth/config' ? 'GET' : 'POST';
349
+ const method = pathname === configRoute || direct ? 'GET' : 'POST';
245
350
  const requestOrigin = request.headers.get('origin');
246
351
  const site = request.headers.get('sec-fetch-site');
247
352
  if (request.method !== method ||
248
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')) ||
249
358
  (method === 'POST' ? requestOrigin !== origin : requestOrigin && requestOrigin !== origin))
250
359
  return problem('not_allowed', 403);
251
360
  try {
252
- if (pathname === '/auth/config')
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
+ }
367
+ if (pathname === configRoute)
253
368
  return reply((await discover(identity)).config);
254
- if (pathname === '/auth/logout')
369
+ if (pathname === logoutRoute)
255
370
  return await logout(request, identity);
256
371
  if (!/^application\/json(?:\s*;.*)?$/i.test(request.headers.get('content-type') ?? ''))
257
372
  return problem('invalid_input', 415);
@@ -262,16 +377,77 @@ export function createSylphxAuthHandler(options) {
262
377
  catch {
263
378
  return problem('invalid_input', 400);
264
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
+ }
393
+ const acceptance = clickwrap ? readAcceptance(input.acceptance) : undefined;
394
+ if ((await accepted(acceptance, request)) !== true)
395
+ return problem('acceptance_required', 403);
265
396
  const next = nextPath(field(input, 'next', 1024));
266
- if (pathname.startsWith(START))
267
- return await start(identity, pathname.slice(START.length), next);
397
+ if (pathname.startsWith(`${startRoute}/`))
398
+ return await start(identity, pathname.slice(startRoute.length + 1), next, acceptance);
268
399
  if (legacy && input.action === 'social')
269
- return await start(identity, input.provider, next);
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
+ }
270
422
  return await emailEntry(identity, input, next, {
271
423
  origin,
272
424
  loginPath,
273
- instance,
274
- session: issue(request),
425
+ mode,
426
+ allowRegistration,
427
+ scope: binding.scope,
428
+ redeem: (ticket) => redeem(identity, ticket),
429
+ session: async (data, method, legacyPassword) => {
430
+ if ((await accepted(acceptance, request)) !== true)
431
+ return problem('acceptance_required', 403);
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);
450
+ },
275
451
  });
276
452
  }
277
453
  catch {
@@ -285,3 +461,41 @@ function sameState(a, b) {
285
461
  difference |= a.charCodeAt(i) ^ b.charCodeAt(i);
286
462
  return difference === 0;
287
463
  }
464
+ function identitySession(data, acceptance, context) {
465
+ const session = obj(data.session);
466
+ const user = obj(data.user);
467
+ if (!token(session.token) || !token(user.id) || typeof user.email_verified !== 'boolean')
468
+ return;
469
+ return {
470
+ ...context,
471
+ token: session.token,
472
+ expiresAt: session.expires_at,
473
+ ...(token(session.id) && { sessionId: session.id }),
474
+ user: {
475
+ id: user.id,
476
+ emailVerified: user.email_verified,
477
+ ...(typeof user.email === 'string' && { email: user.email }),
478
+ ...(typeof user.name === 'string' && { name: user.name }),
479
+ ...(typeof user.username === 'string' && { username: user.username }),
480
+ },
481
+ isNewUser: data.is_new_user === true,
482
+ ...(acceptance && { acceptance }),
483
+ };
484
+ }
485
+ function signUpHeader(response, emit) {
486
+ if (emit)
487
+ response.headers.set('X-Sylphx-Auth-Event', 'sign_up');
488
+ return response;
489
+ }
490
+ function expirySeconds(value) {
491
+ if (typeof value === 'number' || (typeof value === 'string' && /^[0-9]+$/.test(value))) {
492
+ const seconds = Number(value);
493
+ // Limit Unix seconds to year 9999, matching the ISO envelope and rejecting millisecond epochs.
494
+ return Number.isSafeInteger(seconds) && seconds <= 253_402_300_799 ? seconds : NaN;
495
+ }
496
+ if (typeof value !== 'string')
497
+ return NaN;
498
+ if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/i.test(value))
499
+ return NaN;
500
+ return Date.parse(value) / 1000;
501
+ }
@@ -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
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sylphx/auth",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "type": "module",
5
5
  "description": "Web-standard first-party Auth handler and its browser contract",
6
6
  "exports": {