@sylphx/auth 0.1.1 → 0.1.3

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
@@ -24,6 +24,24 @@ Request URL reflects the trusted public origin, or supply `isPublicRequest`
24
24
  with your edge's trusted-origin verification. Never trust caller-supplied
25
25
  forwarded headers alone.
26
26
 
27
+ ### Sylphx Hosting
28
+
29
+ Set `trustSylphxEdge: true` on the handler when **all ingress paths to it are
30
+ restricted to managed literal-host routes** that overwrite `Sylphx-Edge`,
31
+ `X-Forwarded-Host` and `X-Forwarded-Proto` for the matched public hostname.
32
+ This admits the rewritten internal request URL only with `Sylphx-Edge: public`,
33
+ a single exact forwarded host equal to the configured `origin`’s host (including
34
+ any non-default port), and `X-Forwarded-Proto: https`. Partial or contradictory
35
+ headers are rejected even when the request URL matches. With no edge headers,
36
+ the request URL must match the configured HTTPS origin as before.
37
+
38
+ Do not enable this on wildcard, direct-to-service, or other routes where a
39
+ caller can supply either forwarded header. The edge marker is not a credential,
40
+ and the HTTPS stamp is the configured public scheme, not a TLS observation.
41
+ Remove a hand-rolled `isPublicRequest` when adopting this option; that callback
42
+ otherwise retains precedence. Browser Origin and fetch-metadata checks, OAuth
43
+ state checks, and redirect destinations are unchanged.
44
+
27
45
  | Route | Method | Input / result |
28
46
  | --- | --- | --- |
29
47
  | `/auth/config` | GET | Public capabilities only; no credentials or upstream URLs |
@@ -99,3 +117,55 @@ server loader and pass its JSON as the widget's `initialConfig`. Use
99
117
  `allowPasswordRegistration: false` to hide and refuse new password signup via
100
118
  this handler; password sign-in, confirmation of prior registrations, OTP and
101
119
  OAuth remain available according to the instance's capabilities.
120
+
121
+ ## Instance keys and entry policy
122
+
123
+ Pass `publishableKey: env.SYLPHX_PUBLISHABLE_KEY` instead of `instance` to
124
+ resolve the tenant via its Access publishable key. The handler uses the bearer
125
+ header on Identity client calls, never the public config response, browser
126
+ URL, or tenant portal. You can provide both to additionally pin the resolved
127
+ ID, slug and environment. Confidential ticket redemption still uses only the
128
+ server key.
129
+
130
+ Set `allowedMethods: ['oauth', 'otp', 'passkey']`, for example, to suppress and
131
+ reject password sign-in, password MFA, registration, and recovery. An empty
132
+ array denies all sign-in methods. The allowlist is local to this handler.
133
+
134
+ An unverified password sign-in is denied by default. To continue a legacy mail
135
+ proof flow, use `issueUnverifiedPassword` to return a short-lived, proof-only
136
+ cookie. Never grant normal application permissions based on this callback;
137
+ verify the mailed proof against the same principal before upgrading the
138
+ session. The normal `session.issue` callback is never invoked in this case.
139
+
140
+ ## App session integration
141
+
142
+ - `session.issue` also receives `method`, `provider` (OAuth only), and normalized
143
+ `returnTo`. Optional `signUpSignal(context, request)` emits only the fixed
144
+ `X-Sylphx-Auth-Event: sign_up` response header, and only on confirmed new-user
145
+ sign-in with no GPC header. Return true only after checking affirmative,
146
+ current consent. It emits no user or session identifiers, and never changes
147
+ the HttpOnly session headers. Redirect response headers are not exposed to
148
+ browser JS; consume the marker server-side for OAuth.
149
+ - `readAuthSessionCookie(request, { sessionCookie, legacyCookies })` reads
150
+ the preferred credential for your app's auth middleware. A canonical cookie
151
+ takes precedence; malformed or duplicate candidates do not cause fallback.
152
+ Validate the credential with its authoritative issuer before authorizing
153
+ requests or migrating it. Your middleware can then rotate it into the
154
+ canonical cookie without extending its lifetime. The default logout route
155
+ revokes the presented Identity session and clears the configured names;
156
+ a custom adapter owns revocation and cleanup of its own cookies.
157
+ - `passkeyEnrollment: true` enables POST `/auth/passkey/enroll` using the
158
+ canonical or configured legacy Identity session cookie. Hosts with their own
159
+ session store can provide an async resolver for an Identity credential after
160
+ authenticating the app session. Identity checks the tenant, verified email,
161
+ recent session and WebAuthn proof. Use `SylphxPasskeyEnroll` in a signed-in view.
162
+ - `recoverPassword({ email, returnTo }, request)` enables the recovery-start
163
+ action. Handle the send without disclosing account existence, enforce rate
164
+ limits, and validate the mailed proof in your reset page. Identity's recovery
165
+ operations require their own authorization; this hook does not proxy them
166
+ using a publishable key or issue a session.
167
+ - `directOAuth: true` enables GET `/auth/:provider?returnTo=/account` from a
168
+ same-origin top-level browser navigation. External requests, background
169
+ fetches and requests without browser navigation headers cannot start it.
170
+ Apps using server-side clickwrap must use POST `/auth/start/:provider` to
171
+ 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
- instance: Record<string, string>;
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, 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();
@@ -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
- query: instance,
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, { query: instance, body });
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
- 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)
160
162
  return problem('verify_email', 403);
161
- return issue(result);
163
+ return issue(result, method, legacyPassword);
162
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,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 VerifiedIdentitySession = IdentitySession & {
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
- instance: {
36
- slug: string;
37
- id: string;
38
- environment: string;
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[];
@@ -53,12 +78,14 @@ export type SylphxAuthOptions = {
53
78
  allowReturnTo?: (path: string) => boolean;
54
79
  flowCookie?: string;
55
80
  sessionCookie?: string;
56
- /** For an existing edge: check a trusted host binding on the internal request. */
81
+ /** Opt in only on managed literal-host routes that overwrite all three Sylphx Edge headers. */
82
+ trustSylphxEdge?: boolean;
83
+ /** Override the public request check, including the built-in Sylphx Edge policy. */
57
84
  isPublicRequest?: (request: Request) => boolean;
58
85
  /** Only for hosts with an existing authoritative session and revocation mechanism. */
59
86
  session?: SessionAdapter;
60
87
  fetch?: AuthFetch;
61
- } & ({
88
+ } & InstanceBinding & ({
62
89
  sessionMode?: 'browser';
63
90
  sessionSecret?: never;
64
91
  } | {
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')
@@ -44,19 +48,20 @@ function portalStart(provider, row, discovery, pin, slug) {
44
48
  }
45
49
  export function createSylphxAuthHandler(options) {
46
50
  const origin = requireOrigin(options.origin);
51
+ const publicHost = new URL(origin).host;
47
52
  const api = requireOrigin(options.authApiOrigin);
48
53
  const tenantAuthOrigin = options.tenantAuthOrigin === undefined ? undefined : requireOrigin(options.tenantAuthOrigin);
49
54
  if (tenantAuthOrigin && tenantAuthOrigin === api)
50
55
  throw new TypeError('Use the tenant Auth origin, not the Auth API origin');
51
- const { slug, id, environment } = options.instance;
52
- if (!/^[a-z0-9][a-z0-9-]{0,62}$/.test(slug) || !id || !environment)
53
- throw new TypeError('Expected an Auth instance');
54
- const instance = { instance: slug };
56
+ const binding = bindInstance(options);
57
+ const allowed = options.allowedMethods && new Set(options.allowedMethods);
58
+ const allows = (method) => !allowed || allowed.has(method);
55
59
  const prefix = authRoutePrefix(options.routePrefix);
56
60
  const startRoute = `${prefix}/start`;
57
61
  const callbackRoute = `${prefix}/callback`;
58
62
  const configRoute = `${prefix}/config`;
59
63
  const emailRoute = `${prefix}/email`;
64
+ const enrollmentRoute = `${prefix}/passkey/enroll`;
60
65
  const logoutRoute = `${prefix}/logout`;
61
66
  const mode = options.sessionMode ?? 'browser';
62
67
  const secret = options.sessionSecret;
@@ -82,13 +87,17 @@ export function createSylphxAuthHandler(options) {
82
87
  throw new TypeError('Use separate host-only cookie names');
83
88
  const clearFlow = [flowName, '', 0];
84
89
  const callback = origin + callbackRoute;
85
- const signable = (value) => JSON.stringify([callback, id, value]);
90
+ const signable = (value) => JSON.stringify([callback, options.instance?.id ?? options.publishableKey, value]);
91
+ const legacyCookies = (options.legacyCookies ?? []).map(cookieName);
92
+ if (new Set([flowName, sessionName, ...legacyCookies]).size !== legacyCookies.length + 2)
93
+ throw new TypeError('Use distinct session and flow cookie names');
94
+ const sessionSource = (request) => readAuthSessionCookie(request, { sessionCookie: sessionName, legacyCookies });
86
95
  function accepted(versions, request) {
87
96
  return clickwrap ? versions && clickwrap.validate(versions, request) : true;
88
97
  }
89
98
  async function redeem(identity, ticket) {
90
99
  const res = await identity('/v1/client/tickets:redeem', {
91
- query: instance,
100
+ ...binding.scope,
92
101
  body: { ticket },
93
102
  ...(mode === 'server' && secret && { bearer: secret }),
94
103
  });
@@ -101,18 +110,10 @@ export function createSylphxAuthHandler(options) {
101
110
  const fetchUpstream = options.fetch ?? ((url, init) => fetch(url, init));
102
111
  const social = [...new Set(options.providers ?? Object.keys(providers).filter(isProvider))];
103
112
  async function discover(identity) {
104
- const res = await identity('/v1/client/config', { query: instance });
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);
113
+ const { data, instance } = await binding.discover(identity);
113
114
  const redirects = new Map();
114
115
  const rows = Array.isArray(data.social) ? data.social.map(obj) : [];
115
- for (const provider of social) {
116
+ for (const provider of allows('oauth') ? social : []) {
116
117
  const entries = rows.filter((row) => row.provider === provider);
117
118
  if (entries.length !== 1)
118
119
  continue;
@@ -120,31 +121,32 @@ export function createSylphxAuthHandler(options) {
120
121
  if (row.credentials === 'shared')
121
122
  redirects.set(provider, null);
122
123
  else if (row.credentials === 'custom') {
123
- const start = portalStart(provider, row, data, tenantAuthOrigin, slug);
124
+ const start = portalStart(provider, row, data, tenantAuthOrigin, instance.slug);
124
125
  if (start)
125
126
  redirects.set(provider, start);
126
127
  }
127
128
  }
128
- const config = {
129
- providers: [...redirects.keys()],
130
- password: methods.password === true,
131
- signup: allowRegistration && methods.sign_up === true && methods.password === true,
132
- otp: methods.email_otp === true,
133
- passkey: methods.passkey === true,
134
- };
135
- return { config, redirects };
129
+ const config = entryConfig(obj(data.methods), [...redirects.keys()], allows, allowRegistration);
130
+ if (options.recoverPassword)
131
+ config.recovery = config.password;
132
+ if (options.passkeyEnrollment)
133
+ config.passkeyEnrollment = config.passkey;
134
+ return { config, redirects, instance };
136
135
  }
137
- async function start(identity, provider, next, acceptance) {
136
+ async function start(identity, provider, next, acceptance, navigate = false) {
138
137
  if (!isProvider(provider) || !social.includes(provider))
139
138
  return problem('unknown_provider', 400);
140
- const { redirects } = await discover(identity);
139
+ if (!allows('oauth'))
140
+ return problem('method_unavailable', 403);
141
+ const { redirects, instance } = await discover(identity);
141
142
  const start = redirects.get(provider);
142
143
  if (start === undefined)
143
144
  return problem('method_unavailable', 403);
144
145
  const state = random();
145
146
  const expires = Math.floor(Date.now() / 1000) + FLOW_AGE;
146
- const path = encodeURIComponent(next.slice(1)).replaceAll('.', '%2E');
147
- let value = [state, expires, path].join('.');
147
+ const encode = (value) => encodeURIComponent(value).replaceAll('.', '%2E');
148
+ const path = encode(next.slice(1));
149
+ let value = [state, expires, path, provider, encode(instance.id)].join('.');
148
150
  if (signer && acceptance) {
149
151
  value += `.${encodeAcceptance(acceptance)}`;
150
152
  value += `.${await signer.sign(signable(value))}`;
@@ -156,7 +158,12 @@ export function createSylphxAuthHandler(options) {
156
158
  // Auth owns upstream PKCE S256, nonce and Apple's form_post. This
157
159
  // app's GET callback only receives Auth's one-use sign-in ticket.
158
160
  const res = await identity(start?.url ?? `/v1/client/oauth/${provider}/start`, {
159
- query: { ...instance, redirect_url: target.href, session_mode: mode },
161
+ ...(start ? {} : binding.scope),
162
+ query: {
163
+ ...(start ? { instance: instance.slug } : binding.scope.query),
164
+ redirect_url: target.href,
165
+ session_mode: mode,
166
+ },
160
167
  manual: true,
161
168
  });
162
169
  const authorize = res.status === 303 && providerDestination(provider, res.headers.get('location'));
@@ -168,21 +175,34 @@ export function createSylphxAuthHandler(options) {
168
175
  if (callbacks.length !== 1 || callbacks[0] !== start.redirectUri)
169
176
  return problem('method_unavailable', 503);
170
177
  }
171
- return reply({ authorize }, 200, [[flowName, value, FLOW_AGE]]);
178
+ const cookies = [[flowName, value, FLOW_AGE]];
179
+ return navigate ? redirect(authorize, cookies) : reply({ authorize }, 200, cookies);
172
180
  }
173
- function issue(request) {
174
- return async (session) => {
175
- const cookies = options.session
176
- ? await options.session.issue(session, request)
177
- : sessionCookie(session);
178
- if (!cookies?.length)
181
+ function validatedCookies(cookies) {
182
+ if (!cookies?.length)
183
+ return;
184
+ const seen = new Set([flowName]);
185
+ for (const [name, value, age] of cookies) {
186
+ if (seen.has(cookieName(name)) || !token(value) || !Number.isSafeInteger(age) || age < 1)
179
187
  return;
180
- for (const [name, value, age] of cookies) {
181
- if (cookieName(name) === flowName || !token(value) || !Number.isSafeInteger(age) || age < 1)
182
- return;
188
+ seen.add(name);
189
+ }
190
+ return cookies;
191
+ }
192
+ async function issue(request, session, context) {
193
+ const cookies = validatedCookies(options.session ? await options.session.issue(session, request) : sessionCookie(session));
194
+ if (!cookies)
195
+ return;
196
+ let signUp = false;
197
+ if (session.isNewUser && !request.headers.has('sec-gpc')) {
198
+ try {
199
+ signUp = (await options.signUpSignal?.(context, request)) === true;
200
+ }
201
+ catch {
202
+ // Optional analytics must not prevent sign-in.
183
203
  }
184
- return cookies;
185
- };
204
+ }
205
+ return { cookies, signUp };
186
206
  }
187
207
  function sessionCookie(session) {
188
208
  const age = Math.floor(expirySeconds(session.expiresAt) - Date.now() / 1000);
@@ -196,25 +216,33 @@ export function createSylphxAuthHandler(options) {
196
216
  out.append('Set-Cookie', headers([clearFlow]).getSetCookie()[0]);
197
217
  return new Response(res.body, { status: res.status, headers: out });
198
218
  }
199
- const credential = readCookie(request, sessionName);
219
+ const credential = sessionSource(request)?.value;
200
220
  if (token(credential)) {
201
221
  const res = await identity('/v1/client/sign-out', { method: 'POST', bearer: credential });
202
222
  discard(res);
203
223
  if (res.status !== 204)
204
224
  return problem('unavailable', 503);
205
225
  }
206
- return new Response(null, { status: 204, headers: headers([clearFlow, [sessionName, '', 0]]) });
226
+ return new Response(null, {
227
+ status: 204,
228
+ headers: headers([
229
+ clearFlow,
230
+ ...[sessionName, ...legacyCookies].map((name) => [name, '', 0]),
231
+ ]),
232
+ });
207
233
  }
208
234
  async function readFlow(request) {
209
235
  const value = readCookie(request, flowName);
210
236
  if (!value || (signer && value.length > 3600))
211
237
  return;
212
238
  const parts = value.split('.');
213
- if (parts.length !== (signer ? 5 : 3))
239
+ if (parts.length !== (signer ? 7 : 5))
214
240
  return;
215
- const [state, deadline, path, encoded, mac] = parts;
241
+ const [state, deadline, path, provider, instanceId, encoded, mac] = parts;
216
242
  const now = Math.floor(Date.now() / 1000);
217
- if (!state ||
243
+ if (!isProvider(provider) ||
244
+ !instanceId ||
245
+ !state ||
218
246
  !RANDOM.test(state) ||
219
247
  !deadline ||
220
248
  !/^\d{10}$/.test(deadline) ||
@@ -232,7 +260,13 @@ export function createSylphxAuthHandler(options) {
232
260
  if (!acceptance)
233
261
  return;
234
262
  }
235
- return { state, next: nextPath(`/${decodeURIComponent(path ?? '')}`), acceptance };
263
+ return {
264
+ state,
265
+ provider,
266
+ instanceId: decodeURIComponent(instanceId),
267
+ next: nextPath(`/${decodeURIComponent(path ?? '')}`),
268
+ acceptance,
269
+ };
236
270
  }
237
271
  catch {
238
272
  return undefined;
@@ -265,44 +299,84 @@ export function createSylphxAuthHandler(options) {
265
299
  try {
266
300
  if ((await accepted(flow.acceptance, request)) !== true)
267
301
  return fail('acceptance_required');
302
+ if (!allows('oauth') || !social.includes(flow.provider))
303
+ return fail();
304
+ const pinned = options.publishableKey
305
+ ? (await binding.discover(identity)).instance
306
+ : options.instance;
307
+ if (flow.instanceId !== pinned.id)
308
+ return fail();
268
309
  const data = await redeem(identity, ticket);
269
310
  if (!data)
270
311
  return fail();
271
- if (obj(data.user).email_verified !== true)
272
- return fail('use_existing');
273
- const session = verifiedSession(data, flow.acceptance);
312
+ const context = {
313
+ method: 'oauth',
314
+ provider: flow.provider,
315
+ returnTo: flow.next,
316
+ };
317
+ const session = identitySession(data, flow.acceptance, context);
274
318
  if (!session)
275
319
  return fail();
320
+ if (!session.user.emailVerified)
321
+ return fail('use_existing');
276
322
  if ((await accepted(flow.acceptance, request)) !== true)
277
323
  return fail('acceptance_required');
278
- const cookies = await issue(request)(session);
279
- return cookies ? redirect(flow.next, [clearFlow, ...cookies]) : fail();
324
+ const issued = await issue(request, { ...session, user: { ...session.user, emailVerified: true } }, context);
325
+ return issued
326
+ ? signUpHeader(redirect(flow.next, [clearFlow, ...issued.cookies]), issued.signUp)
327
+ : fail();
280
328
  }
281
329
  catch {
282
330
  return fail();
283
331
  }
284
332
  }
333
+ function isPublicRequest(request, url) {
334
+ if (options.trustSylphxEdge === true) {
335
+ const edge = request.headers.get('sylphx-edge');
336
+ const host = request.headers.get('x-forwarded-host');
337
+ const proto = request.headers.get('x-forwarded-proto');
338
+ if (edge !== null || host !== null || proto !== null) {
339
+ // Exact comparisons reject combined duplicates and never choose a list entry.
340
+ return edge === 'public' && host === publicHost && proto === 'https';
341
+ }
342
+ }
343
+ return url.origin === origin;
344
+ }
285
345
  return async (request) => {
286
346
  const url = new URL(request.url);
287
- if (!(options.isPublicRequest?.(request) ?? url.origin === origin))
347
+ if (!(options.isPublicRequest?.(request) ?? isPublicRequest(request, url)))
288
348
  return problem('not_allowed', 403);
289
349
  const { pathname } = url;
290
350
  const identity = transport(request, fetchUpstream, api);
291
351
  if (pathname === callbackRoute)
292
352
  return request.method === 'GET' ? complete(request, url, identity) : problem('not_found', 404);
353
+ const direct = options.directOAuth &&
354
+ pathname.startsWith(`${prefix}/`) &&
355
+ isProvider(pathname.slice(prefix.length + 1));
293
356
  const legacy = options.legacyStart && pathname === startRoute;
294
- if (!legacy &&
295
- ![configRoute, emailRoute, logoutRoute].includes(pathname) &&
357
+ if (!direct &&
358
+ !legacy &&
359
+ ![configRoute, emailRoute, logoutRoute, enrollmentRoute].includes(pathname) &&
296
360
  !pathname.startsWith(`${startRoute}/`))
297
361
  return problem('not_found', 404);
298
- const method = pathname === configRoute ? 'GET' : 'POST';
362
+ const method = pathname === configRoute || direct ? 'GET' : 'POST';
299
363
  const requestOrigin = request.headers.get('origin');
300
364
  const site = request.headers.get('sec-fetch-site');
301
365
  if (request.method !== method ||
302
366
  (site && site !== 'same-origin') ||
367
+ (direct &&
368
+ (site !== 'same-origin' ||
369
+ request.headers.get('sec-fetch-mode') !== 'navigate' ||
370
+ request.headers.get('sec-fetch-dest') !== 'document')) ||
303
371
  (method === 'POST' ? requestOrigin !== origin : requestOrigin && requestOrigin !== origin))
304
372
  return problem('not_allowed', 403);
305
373
  try {
374
+ if (direct) {
375
+ if (clickwrap)
376
+ return problem('acceptance_required', 403);
377
+ const next = nextPath(url.searchParams.get('returnTo') ?? url.searchParams.get('next'));
378
+ return await start(identity, pathname.slice(prefix.length + 1), next, undefined, true);
379
+ }
306
380
  if (pathname === configRoute)
307
381
  return reply((await discover(identity)).config);
308
382
  if (pathname === logoutRoute)
@@ -316,6 +390,19 @@ export function createSylphxAuthHandler(options) {
316
390
  catch {
317
391
  return problem('invalid_input', 400);
318
392
  }
393
+ if (pathname === enrollmentRoute) {
394
+ if (!options.passkeyEnrollment || !allows('passkey'))
395
+ return problem('method_unavailable', 403);
396
+ const credential = options.passkeyEnrollment === true
397
+ ? sessionSource(request)?.value
398
+ : await options.passkeyEnrollment(request);
399
+ if (!token(credential))
400
+ return problem('not_allowed', 403);
401
+ const { config, instance } = await discover(identity);
402
+ if (!config.passkey)
403
+ return problem('method_unavailable', 403);
404
+ return await enrollPasskey(identity, credential, instance.id, origin, input);
405
+ }
319
406
  const acceptance = clickwrap ? readAcceptance(input.acceptance) : undefined;
320
407
  if ((await accepted(acceptance, request)) !== true)
321
408
  return problem('acceptance_required', 403);
@@ -324,19 +411,55 @@ export function createSylphxAuthHandler(options) {
324
411
  return await start(identity, pathname.slice(startRoute.length + 1), next, acceptance);
325
412
  if (legacy && input.action === 'social')
326
413
  return await start(identity, input.provider, next, acceptance);
414
+ if (typeof input.action !== 'string' || !Object.hasOwn(emailMethods, input.action))
415
+ return problem('not_found', 404);
416
+ const method = emailMethods[input.action];
417
+ if (!allows(method) || (input.action === 'recovery_start' && !options.recoverPassword))
418
+ return problem('method_unavailable', 403);
419
+ if (allowed ||
420
+ (options.instance && options.publishableKey) ||
421
+ input.action === 'recovery_start') {
422
+ const { config } = await discover(identity);
423
+ if (!config[method] || (input.action === 'signup' && !config.signup))
424
+ return problem('method_unavailable', 403);
425
+ }
426
+ if (input.action === 'recovery_start') {
427
+ if (!options.recoverPassword)
428
+ return problem('method_unavailable', 403);
429
+ const email = field(input, 'email', 254)?.trim();
430
+ if (!email || !/^[^\s@]+@[^\s@]+$/.test(email))
431
+ return problem('invalid_input', 400);
432
+ await options.recoverPassword({ email, returnTo: next }, request);
433
+ return reply({ step: 'recovery_sent' }, 202);
434
+ }
327
435
  return await emailEntry(identity, input, next, {
328
436
  origin,
329
437
  loginPath,
330
- instance,
331
438
  mode,
332
439
  allowRegistration,
440
+ scope: binding.scope,
333
441
  redeem: (ticket) => redeem(identity, ticket),
334
- session: async (data) => {
442
+ session: async (data, method, legacyPassword) => {
335
443
  if ((await accepted(acceptance, request)) !== true)
336
444
  return problem('acceptance_required', 403);
337
- const session = verifiedSession(data, acceptance);
338
- const cookies = session && (await issue(request)(session));
339
- return cookies ? reply({ next }, 200, cookies) : problem('session_unavailable', 502);
445
+ const context = { method, returnTo: next };
446
+ const session = identitySession(data, acceptance, context);
447
+ if (!session)
448
+ return problem('session_unavailable', 502);
449
+ if (session.user.emailVerified === false) {
450
+ if (!legacyPassword || !options.issueUnverifiedPassword)
451
+ return problem('verify_email', 403);
452
+ const cookies = validatedCookies(await options.issueUnverifiedPassword({
453
+ ...session,
454
+ method: 'password',
455
+ user: { ...session.user, emailVerified: false },
456
+ }, request));
457
+ return cookies ? reply({ next }, 200, cookies) : problem('verify_email', 403);
458
+ }
459
+ const issued = await issue(request, { ...session, user: { ...session.user, emailVerified: true } }, context);
460
+ return issued
461
+ ? signUpHeader(reply({ next }, 200, issued.cookies), issued.signUp)
462
+ : problem('session_unavailable', 502);
340
463
  },
341
464
  });
342
465
  }
@@ -351,18 +474,19 @@ function sameState(a, b) {
351
474
  difference |= a.charCodeAt(i) ^ b.charCodeAt(i);
352
475
  return difference === 0;
353
476
  }
354
- function verifiedSession(data, acceptance) {
477
+ function identitySession(data, acceptance, context) {
355
478
  const session = obj(data.session);
356
479
  const user = obj(data.user);
357
- if (!token(session.token) || !token(user.id) || user.email_verified !== true)
480
+ if (!token(session.token) || !token(user.id) || typeof user.email_verified !== 'boolean')
358
481
  return;
359
482
  return {
483
+ ...context,
360
484
  token: session.token,
361
485
  expiresAt: session.expires_at,
362
486
  ...(token(session.id) && { sessionId: session.id }),
363
487
  user: {
364
488
  id: user.id,
365
- emailVerified: true,
489
+ emailVerified: user.email_verified,
366
490
  ...(typeof user.email === 'string' && { email: user.email }),
367
491
  ...(typeof user.name === 'string' && { name: user.name }),
368
492
  ...(typeof user.username === 'string' && { username: user.username }),
@@ -371,6 +495,11 @@ function verifiedSession(data, acceptance) {
371
495
  ...(acceptance && { acceptance }),
372
496
  };
373
497
  }
498
+ function signUpHeader(response, emit) {
499
+ if (emit)
500
+ response.headers.set('X-Sylphx-Auth-Event', 'sign_up');
501
+ return response;
502
+ }
374
503
  function expirySeconds(value) {
375
504
  if (typeof value === 'number' || (typeof value === 'string' && /^[0-9]+$/.test(value))) {
376
505
  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
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sylphx/auth",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "type": "module",
5
5
  "description": "Web-standard first-party Auth handler and its browser contract",
6
6
  "exports": {