@sylphx/auth 0.0.0-stage → 0.1.1

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