@sylphx/auth 0.1.0 → 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/README.md CHANGED
@@ -52,3 +52,50 @@ Install this package with your package manager. Use a registry version from the
52
52
  shared clients release, and Node 22.12 or later (or a worker that supplies the
53
53
  standard Fetch and Web Crypto APIs). The existing `@sylphx/sdk` and React imports
54
54
  are unchanged.
55
+
56
+ ## Confidential sign-in and versioned acceptance
57
+
58
+ Set `sessionMode: 'server'` and `sessionSecret` to the instance environment's Access
59
+ secret key with `auth:admin`. The handler requests a one-use ticket for OTP,
60
+ password (including MFA), passkey, and OAuth, then redeems it against the
61
+ configured Auth API. Only redemption receives the secret. The browser gets
62
+ an HttpOnly cookie and a local navigation target, never a bearer or an email
63
+ or passkey ticket in JSON. A failed redemption never falls back to browser
64
+ mode. Omit both options to keep the existing browser-mode upstream contract.
65
+
66
+ The optional `session.issue(session, request)` adapter receives `session.user`
67
+ (verified ID, email status, and profile fields Auth supplied), `sessionId` when
68
+ present, `isNewUser` (false if Auth omits `is_new_user`), and `acceptance` when
69
+ configured. It retains the existing `token` and raw `expiresAt` fields. An adapter
70
+ returns its own cookie tuples and supplies the matching `session.logout` hook.
71
+ The default cookie supports Unix seconds (number or decimal string) and ISO
72
+ timestamps with explicit timezones.
73
+
74
+ For clickwrap, the host shows its own copy and sends an `acceptance` map after
75
+ explicit agreement, e.g. `{ terms: 'v2', privacy: '2026-11-24' }`. Configure
76
+ `clickwrap` on the server to require and validate the map:
77
+
78
+ ```ts
79
+ const clickwrap = {
80
+ signingKey: serverEnv.AUTH_CLICKWRAP_KEY, // independent, random, shared by all app replicas
81
+ validate: (versions: Readonly<Record<string, string>>) =>
82
+ versions.terms === currentTermsVersion && versions.privacy === currentPrivacyVersion,
83
+ }
84
+ ```
85
+
86
+ The validator is a repeatable, read-only policy check, not an audit hook.
87
+ The handler checks consent before starting sign-in and before issuing app
88
+ cookies. For OAuth, the signed flow cookie binds the versions to the callback;
89
+ if policy changed during the redirect, the app asks the user to accept again.
90
+ For OTP, MFA, password, and passkey, include acceptance in each POST. The host
91
+ owns its evidence store and can record the accepted versions for the verified
92
+ principal in `session.issue` before returning cookies. This only gates sessions
93
+ issued through this handler; it does not change Auth instance policy or revoke
94
+ sessions that already exist.
95
+
96
+ Mount under another path with `routePrefix: '/account/auth'` and give the Solid
97
+ widget the same prefix. For SSR, call the handler's GET config route from your
98
+ server loader and pass its JSON as the widget's `initialConfig`. Use
99
+ `allowPasswordRegistration: false` to hide and refuse new password signup via
100
+ this handler; password sign-in, confirmation of prior registrations, OTP and
101
+ OAuth remain available according to the instance's capabilities.
@@ -0,0 +1,14 @@
1
+ export type AcceptanceVersions = Readonly<Record<string, string>>;
2
+ export type ClickwrapPolicy = {
3
+ /** Shared, high-entropy server-only key (at least 32 UTF-8 bytes). */
4
+ signingKey: string;
5
+ /** Check the submitted versions against current policy. Only true permits sign-in. */
6
+ validate(versions: AcceptanceVersions, request: Request): boolean | Promise<boolean>;
7
+ };
8
+ export declare function readAcceptance(value: unknown): AcceptanceVersions | undefined;
9
+ export declare function acceptanceSigner(secret: string): {
10
+ sign(value: string): Promise<string>;
11
+ verify(value: string, mac: string): Promise<boolean>;
12
+ };
13
+ export declare function encodeAcceptance(versions: AcceptanceVersions): string;
14
+ export declare function decodeAcceptance(value: string): AcceptanceVersions | undefined;
@@ -0,0 +1,48 @@
1
+ import { RANDOM } from './http.js';
2
+ export function readAcceptance(value) {
3
+ if (!value || typeof value !== 'object' || Array.isArray(value))
4
+ return;
5
+ const entries = Object.entries(value);
6
+ if (!entries.length || entries.length > 8)
7
+ return;
8
+ const valid = entries.every(([key, version]) => /^[A-Za-z0-9][A-Za-z0-9_-]{0,31}$/.test(key) &&
9
+ typeof version === 'string' &&
10
+ /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/.test(version));
11
+ return valid ? Object.freeze(Object.assign(Object.create(null), value)) : undefined;
12
+ }
13
+ export function acceptanceSigner(secret) {
14
+ const encoder = new TextEncoder();
15
+ const bytes = encoder.encode(secret);
16
+ if (bytes.byteLength < 32)
17
+ throw new TypeError('Expected a high-entropy clickwrap signing key');
18
+ const key = () => crypto.subtle.importKey('raw', bytes, { name: 'HMAC', hash: 'SHA-256' }, false, [
19
+ 'sign',
20
+ 'verify',
21
+ ]);
22
+ return {
23
+ async sign(value) {
24
+ return encode(new Uint8Array(await crypto.subtle.sign('HMAC', await key(), encoder.encode(value))));
25
+ },
26
+ async verify(value, mac) {
27
+ return (RANDOM.test(mac) &&
28
+ crypto.subtle.verify('HMAC', await key(), decode(mac), encoder.encode(value)));
29
+ },
30
+ };
31
+ }
32
+ function encode(bytes) {
33
+ return btoa(String.fromCharCode(...bytes))
34
+ .replaceAll('+', '-')
35
+ .replaceAll('/', '_')
36
+ .replace(/=+$/, '');
37
+ }
38
+ function decode(value) {
39
+ return Uint8Array.from(atob(value.replaceAll('-', '+').replaceAll('_', '/')), (c) => c.charCodeAt(0));
40
+ }
41
+ export function encodeAcceptance(versions) {
42
+ return encode(new TextEncoder().encode(JSON.stringify(versions)));
43
+ }
44
+ export function decodeAcceptance(value) {
45
+ if (!/^[A-Za-z0-9_-]{1,1100}$/.test(value))
46
+ return;
47
+ return readAcceptance(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(decode(value))));
48
+ }
package/dist/client.d.ts CHANGED
@@ -17,3 +17,5 @@ export declare function isProvider(id: unknown): id is Provider;
17
17
  export declare function providerDestination(id: Provider, location: unknown): string | undefined;
18
18
  /** Never return an absolute or protocol-relative URL, even after normalization. */
19
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 CHANGED
@@ -42,3 +42,9 @@ function relativePath(value) {
42
42
  export function safeReturnTo(value, fallback = '/') {
43
43
  return relativePath(value) ?? relativePath(fallback) ?? '/';
44
44
  }
45
+ /** Resolve the canonical same-origin mount used by the handler and widget. */
46
+ export function authRoutePrefix(value = '/auth') {
47
+ if (!/^\/(?:[A-Za-z0-9_-]+\/)*[A-Za-z0-9_-]+$/.test(value))
48
+ throw new TypeError('Expected a canonical Auth route prefix');
49
+ return value;
50
+ }
package/dist/email.d.ts CHANGED
@@ -1,9 +1,11 @@
1
1
  import { type Data, type Identity } from './http.js';
2
- import type { IssueSession } from './server.js';
3
2
  export declare function refused(res: Response, error: string): Response;
4
3
  export declare function emailEntry(identity: Identity, input: Data, next: string, ctx: {
5
4
  origin: string;
6
5
  loginPath: string;
7
6
  instance: Record<string, string>;
8
- session: IssueSession;
7
+ mode: 'server' | 'browser';
8
+ allowRegistration: boolean;
9
+ redeem(ticket: string): Promise<Data | undefined>;
10
+ session(data: Data): Promise<Response>;
9
11
  }): Promise<Response>;
package/dist/email.js CHANGED
@@ -15,7 +15,7 @@ export async function emailEntry(identity, input, next, ctx) {
15
15
  const password = field(input, 'password', 1024);
16
16
  const code = field(input, 'code', 128);
17
17
  let path;
18
- let body = { session_mode: 'browser' };
18
+ let body = { session_mode: ctx.mode };
19
19
  const challengeId = field(input, 'challengeId', 200);
20
20
  const secret = field(input, 'verification', 256);
21
21
  const verification = token(challengeId) && token(secret)
@@ -33,6 +33,8 @@ export async function emailEntry(identity, input, next, ctx) {
33
33
  break;
34
34
  }
35
35
  case 'signup': {
36
+ if (!ctx.allowRegistration)
37
+ return problem('method_unavailable', 403);
36
38
  if (!email ||
37
39
  !password ||
38
40
  new TextEncoder().encode(password).byteLength < 12 ||
@@ -133,9 +135,13 @@ export async function emailEntry(identity, input, next, ctx) {
133
135
  });
134
136
  if (action === 'otp_start' || action === 'passkey_start')
135
137
  return problem('unavailable', 502);
136
- const session = obj(data.session);
138
+ const ticket = data.ticket;
139
+ const result = ctx.mode === 'server' ? token(ticket) && (await ctx.redeem(ticket)) : data;
140
+ if (!result)
141
+ return problem('session_unavailable', 502);
142
+ const session = obj(result.session);
137
143
  const credential = session.token;
138
- const user = obj(data.user);
144
+ const user = obj(result.user);
139
145
  if (!token(credential) || !token(user.id))
140
146
  return problem('unavailable', 502);
141
147
  if (verification && (action === 'verify_signup' || action === 'mfa')) {
@@ -148,9 +154,9 @@ export async function emailEntry(identity, input, next, ctx) {
148
154
  const result = await json(confirmed);
149
155
  if (!confirmed.ok || obj(result.verification).principal_id !== user.id)
150
156
  return refused(confirmed, 'verification_failed');
157
+ user.email_verified = true;
151
158
  }
152
159
  else if (user.email_verified !== true)
153
160
  return problem('verify_email', 403);
154
- const cookies = await issue({ token: credential, expiresAt: session.expires_at });
155
- return cookies ? reply({ next }, 200, cookies) : problem('session_unavailable', 502);
161
+ return issue(result);
156
162
  }
package/dist/server.d.ts CHANGED
@@ -1,5 +1,7 @@
1
+ import { type AcceptanceVersions, type ClickwrapPolicy } from './acceptance.js';
1
2
  import { type Provider } from './client.js';
2
3
  import { type AuthCookie, type AuthFetch } from './http.js';
4
+ export type { AcceptanceVersions, ClickwrapPolicy } from './acceptance.js';
3
5
  export type { AuthCookie, AuthFetch } from './http.js';
4
6
  export { jsonBody as readAuthJson } from './http.js';
5
7
  export { exchangeManagementSession } from './session.js';
@@ -8,8 +10,21 @@ export type IdentitySession = {
8
10
  expiresAt: unknown;
9
11
  };
10
12
  export type IssueSession = (session: IdentitySession) => Promise<readonly AuthCookie[] | undefined>;
11
- type SessionAdapter = {
12
- issue(session: IdentitySession, request: Request): ReturnType<IssueSession>;
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>;
13
28
  logout(request: Request): Promise<Response>;
14
29
  };
15
30
  export type SylphxAuthOptions = {
@@ -28,6 +43,12 @@ export type SylphxAuthOptions = {
28
43
  /** Transitional alias for a preexisting client that posts action and provider to /auth/start. */
29
44
  legacyStart?: boolean;
30
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;
31
52
  defaultReturnTo?: string;
32
53
  allowReturnTo?: (path: string) => boolean;
33
54
  flowCookie?: string;
@@ -37,5 +58,11 @@ export type SylphxAuthOptions = {
37
58
  /** Only for hosts with an existing authoritative session and revocation mechanism. */
38
59
  session?: SessionAdapter;
39
60
  fetch?: AuthFetch;
40
- };
61
+ } & ({
62
+ sessionMode?: 'browser';
63
+ sessionSecret?: never;
64
+ } | {
65
+ sessionMode: 'server';
66
+ sessionSecret: string;
67
+ });
41
68
  export declare function createSylphxAuthHandler(options: SylphxAuthOptions): (request: Request) => Promise<Response>;
package/dist/server.js CHANGED
@@ -1,11 +1,10 @@
1
- import { isProvider, providerDestination, providers, safeReturnTo, } from './client.js';
1
+ import { acceptanceSigner, decodeAcceptance, encodeAcceptance, readAcceptance, } from './acceptance.js';
2
+ import { authRoutePrefix, isProvider, providerDestination, providers, safeReturnTo, } from './client.js';
2
3
  import { emailEntry } from './email.js';
3
4
  import { cookieName, discard, field, headers, json, jsonBody, obj, problem, RANDOM, random, readCookie, redirect, reply, token, transport, } from './http.js';
4
5
  export { jsonBody as readAuthJson } from './http.js';
5
6
  export { exchangeManagementSession } from './session.js';
6
7
  const FLOW_AGE = 600;
7
- const START = '/auth/start/';
8
- const CALLBACK = '/auth/callback';
9
8
  function secureUrl(value) {
10
9
  if (typeof value !== 'string')
11
10
  return;
@@ -53,6 +52,21 @@ export function createSylphxAuthHandler(options) {
53
52
  if (!/^[a-z0-9][a-z0-9-]{0,62}$/.test(slug) || !id || !environment)
54
53
  throw new TypeError('Expected an Auth instance');
55
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;
56
70
  const loginPath = safeReturnTo(options.loginPath, '/login');
57
71
  if (/[?#]/.test(loginPath))
58
72
  throw new TypeError('Expected a login pathname');
@@ -67,7 +81,23 @@ export function createSylphxAuthHandler(options) {
67
81
  ![flowName, sessionName].every((name) => name.startsWith('__Host-')))
68
82
  throw new TypeError('Use separate host-only cookie names');
69
83
  const clearFlow = [flowName, '', 0];
70
- const callback = origin + CALLBACK;
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
+ }
71
101
  const fetchUpstream = options.fetch ?? ((url, init) => fetch(url, init));
72
102
  const social = [...new Set(options.providers ?? Object.keys(providers).filter(isProvider))];
73
103
  async function discover(identity) {
@@ -98,13 +128,13 @@ export function createSylphxAuthHandler(options) {
98
128
  const config = {
99
129
  providers: [...redirects.keys()],
100
130
  password: methods.password === true,
101
- signup: methods.sign_up === true && methods.password === true,
131
+ signup: allowRegistration && methods.sign_up === true && methods.password === true,
102
132
  otp: methods.email_otp === true,
103
133
  passkey: methods.passkey === true,
104
134
  };
105
135
  return { config, redirects };
106
136
  }
107
- async function start(identity, provider, next) {
137
+ async function start(identity, provider, next, acceptance) {
108
138
  if (!isProvider(provider) || !social.includes(provider))
109
139
  return problem('unknown_provider', 400);
110
140
  const { redirects } = await discover(identity);
@@ -112,12 +142,21 @@ export function createSylphxAuthHandler(options) {
112
142
  if (start === undefined)
113
143
  return problem('method_unavailable', 403);
114
144
  const state = random();
145
+ const expires = Math.floor(Date.now() / 1000) + FLOW_AGE;
146
+ const 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
+ }
115
154
  const target = new URL(callback);
116
155
  target.searchParams.set('flow', state);
117
156
  // Auth owns upstream PKCE S256, nonce and Apple's form_post. This
118
157
  // app's GET callback only receives Auth's one-use sign-in ticket.
119
158
  const res = await identity(start?.url ?? `/v1/client/oauth/${provider}/start`, {
120
- query: { ...instance, redirect_url: target.href, session_mode: 'browser' },
159
+ query: { ...instance, redirect_url: target.href, session_mode: mode },
121
160
  manual: true,
122
161
  });
123
162
  const authorize = res.status === 303 && providerDestination(provider, res.headers.get('location'));
@@ -129,9 +168,7 @@ export function createSylphxAuthHandler(options) {
129
168
  if (callbacks.length !== 1 || callbacks[0] !== start.redirectUri)
130
169
  return problem('method_unavailable', 503);
131
170
  }
132
- const expires = Math.floor(Date.now() / 1000) + FLOW_AGE;
133
- const path = encodeURIComponent(next.slice(1)).replaceAll('.', '%2E');
134
- return reply({ authorize }, 200, [[flowName, [state, expires, path].join('.'), FLOW_AGE]]);
171
+ return reply({ authorize }, 200, [[flowName, value, FLOW_AGE]]);
135
172
  }
136
173
  function issue(request) {
137
174
  return async (session) => {
@@ -148,9 +185,8 @@ export function createSylphxAuthHandler(options) {
148
185
  };
149
186
  }
150
187
  function sessionCookie(session) {
151
- const expires = typeof session.expiresAt === 'string' ? Date.parse(session.expiresAt) : NaN;
152
- const age = Math.floor((expires - Date.now()) / 1000);
153
- return Number.isFinite(age) && age >= 1 ? [[sessionName, session.token, age]] : undefined;
188
+ const age = Math.floor(expirySeconds(session.expiresAt) - Date.now() / 1000);
189
+ return Number.isSafeInteger(age) && age >= 1 ? [[sessionName, session.token, age]] : undefined;
154
190
  }
155
191
  async function logout(request, identity) {
156
192
  if (options.session) {
@@ -169,11 +205,14 @@ export function createSylphxAuthHandler(options) {
169
205
  }
170
206
  return new Response(null, { status: 204, headers: headers([clearFlow, [sessionName, '', 0]]) });
171
207
  }
172
- function readFlow(request) {
173
- const parts = readCookie(request, flowName)?.split('.');
174
- if (parts?.length !== 3)
208
+ async function readFlow(request) {
209
+ const value = readCookie(request, flowName);
210
+ if (!value || (signer && value.length > 3600))
175
211
  return;
176
- const [state, deadline, path] = parts;
212
+ const parts = value.split('.');
213
+ if (parts.length !== (signer ? 5 : 3))
214
+ return;
215
+ const [state, deadline, path, encoded, mac] = parts;
177
216
  const now = Math.floor(Date.now() / 1000);
178
217
  if (!state ||
179
218
  !RANDOM.test(state) ||
@@ -183,14 +222,24 @@ export function createSylphxAuthHandler(options) {
183
222
  Number(deadline) > now + FLOW_AGE)
184
223
  return;
185
224
  try {
186
- return { state, next: nextPath(`/${decodeURIComponent(path ?? '')}`) };
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 };
187
236
  }
188
237
  catch {
189
238
  return undefined;
190
239
  }
191
240
  }
192
241
  async function complete(request, url, identity) {
193
- const flow = readFlow(request);
242
+ const flow = await readFlow(request);
194
243
  const fail = (error = 'signin') => redirect(`${loginPath}?${new URLSearchParams({ error, next: flow?.next ?? fallback })}`, [
195
244
  clearFlow,
196
245
  ]);
@@ -214,14 +263,19 @@ export function createSylphxAuthHandler(options) {
214
263
  if (tickets.length !== 1 || !token(ticket))
215
264
  return fail();
216
265
  try {
217
- const res = await identity('/v1/client/tickets:redeem', { query: instance, body: { ticket } });
218
- const data = await json(res);
219
- const session = obj(data.session);
220
- if (!res.ok || !token(session.token))
266
+ if ((await accepted(flow.acceptance, request)) !== true)
267
+ return fail('acceptance_required');
268
+ const data = await redeem(identity, ticket);
269
+ if (!data)
221
270
  return fail();
222
271
  if (obj(data.user).email_verified !== true)
223
272
  return fail('use_existing');
224
- const cookies = await issue(request)({ token: session.token, expiresAt: session.expires_at });
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);
225
279
  return cookies ? redirect(flow.next, [clearFlow, ...cookies]) : fail();
226
280
  }
227
281
  catch {
@@ -234,14 +288,14 @@ export function createSylphxAuthHandler(options) {
234
288
  return problem('not_allowed', 403);
235
289
  const { pathname } = url;
236
290
  const identity = transport(request, fetchUpstream, api);
237
- if (pathname === CALLBACK)
291
+ if (pathname === callbackRoute)
238
292
  return request.method === 'GET' ? complete(request, url, identity) : problem('not_found', 404);
239
- const legacy = options.legacyStart && pathname === '/auth/start';
293
+ const legacy = options.legacyStart && pathname === startRoute;
240
294
  if (!legacy &&
241
- !['/auth/config', '/auth/email', '/auth/logout'].includes(pathname) &&
242
- !pathname.startsWith(START))
295
+ ![configRoute, emailRoute, logoutRoute].includes(pathname) &&
296
+ !pathname.startsWith(`${startRoute}/`))
243
297
  return problem('not_found', 404);
244
- const method = pathname === '/auth/config' ? 'GET' : 'POST';
298
+ const method = pathname === configRoute ? 'GET' : 'POST';
245
299
  const requestOrigin = request.headers.get('origin');
246
300
  const site = request.headers.get('sec-fetch-site');
247
301
  if (request.method !== method ||
@@ -249,9 +303,9 @@ export function createSylphxAuthHandler(options) {
249
303
  (method === 'POST' ? requestOrigin !== origin : requestOrigin && requestOrigin !== origin))
250
304
  return problem('not_allowed', 403);
251
305
  try {
252
- if (pathname === '/auth/config')
306
+ if (pathname === configRoute)
253
307
  return reply((await discover(identity)).config);
254
- if (pathname === '/auth/logout')
308
+ if (pathname === logoutRoute)
255
309
  return await logout(request, identity);
256
310
  if (!/^application\/json(?:\s*;.*)?$/i.test(request.headers.get('content-type') ?? ''))
257
311
  return problem('invalid_input', 415);
@@ -262,16 +316,28 @@ export function createSylphxAuthHandler(options) {
262
316
  catch {
263
317
  return problem('invalid_input', 400);
264
318
  }
319
+ const acceptance = clickwrap ? readAcceptance(input.acceptance) : undefined;
320
+ if ((await accepted(acceptance, request)) !== true)
321
+ return problem('acceptance_required', 403);
265
322
  const next = nextPath(field(input, 'next', 1024));
266
- if (pathname.startsWith(START))
267
- return await start(identity, pathname.slice(START.length), next);
323
+ if (pathname.startsWith(`${startRoute}/`))
324
+ return await start(identity, pathname.slice(startRoute.length + 1), next, acceptance);
268
325
  if (legacy && input.action === 'social')
269
- return await start(identity, input.provider, next);
326
+ return await start(identity, input.provider, next, acceptance);
270
327
  return await emailEntry(identity, input, next, {
271
328
  origin,
272
329
  loginPath,
273
330
  instance,
274
- session: issue(request),
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
+ },
275
341
  });
276
342
  }
277
343
  catch {
@@ -285,3 +351,35 @@ function sameState(a, b) {
285
351
  difference |= a.charCodeAt(i) ^ b.charCodeAt(i);
286
352
  return difference === 0;
287
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
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sylphx/auth",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "type": "module",
5
5
  "description": "Web-standard first-party Auth handler and its browser contract",
6
6
  "exports": {