dsh-cindy-host 0.1.32 → 0.1.34

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.
@@ -13,6 +13,7 @@
13
13
  import { randomUUID } from 'node:crypto';
14
14
  import { loginWithPhone } from './cindy-login.js';
15
15
  import { refreshStoredSession } from './cindy-login-flow.js';
16
+ import { sessionEndpoints } from './cindy-auth-endpoints.js';
16
17
  import { loadSession, saveSession, credentialStoreAvailable, clearSession as clearStoredSession } from './credential-store.js';
17
18
 
18
19
  // One in-process writer for login/logout and guarded refresh commits. This is
@@ -26,8 +27,14 @@ function serializeWrite(action) {
26
27
  }
27
28
  function sameCredential(a, b) {
28
29
  return a != null && b != null && ['deviceId', 'authBaseUrl', 'accessToken', 'refreshToken']
29
- .every((key) => a[key] === b[key]);
30
+ .every((key) => a[key] === b[key]) && a.realm === b.realm
31
+ && JSON.stringify(a.endpointSnapshot ?? null) === JSON.stringify(b.endpointSnapshot ?? null);
30
32
  }
33
+ function validRealmMetadata(session) {
34
+ if (!session?.endpointSnapshot && session?.sessionVersion !== 2 && session?.realm === undefined) return true;
35
+ try { return sessionEndpoints(session) !== null; } catch { return false; }
36
+ }
37
+ const invalidRealm = () => ({ ok: false, reason: 'SESSION_REALM_MISMATCH', message: 'Cindy 账号区域配置无效,请重新登录' });
31
38
  const superseded = () => ({ ok: false, reason: 'OWNER_UNVERIFIED', message: 'Cindy 登录归属已变化,未采用旧操作结果' });
32
39
 
33
40
  /** Refresh only a captured authenticated lease, never import another stored identity. */
@@ -38,6 +45,7 @@ export async function refreshOwnedCredential(captured, ports = {}) {
38
45
  const current = ports.isCurrent ?? (() => false);
39
46
  const revision = credentialRevision;
40
47
  const snapshot = Object.freeze({ ...captured });
48
+ if (!validRealmMetadata(snapshot)) return invalidRealm();
41
49
  const stored = await load();
42
50
  if (revision !== credentialRevision || !current() || !sameCredential(snapshot, stored)) return superseded();
43
51
  const timeoutMs = Number.isSafeInteger(ports.timeoutMs) && ports.timeoutMs > 0 ? Math.min(ports.timeoutMs, 30_000) : 30_000;
@@ -68,6 +76,7 @@ export async function refreshOwnedCredential(captured, ports = {}) {
68
76
  }
69
77
  if (!refreshed?.ok) return { ok: false, reason: 'AUTH_FAILED', message: 'Cindy 登录续期失败' };
70
78
  const session = { ...snapshot, ...refreshed.session };
79
+ if (!validRealmMetadata(session)) return invalidRealm();
71
80
  if (session.deviceId !== snapshot.deviceId || session.authBaseUrl !== snapshot.authBaseUrl
72
81
  || typeof session.accessToken !== 'string' || !session.accessToken
73
82
  || typeof session.refreshToken !== 'string' || !session.refreshToken) return superseded();
@@ -107,12 +116,14 @@ export async function restoreSession(ports = {}) {
107
116
  const revision = credentialRevision;
108
117
  const saved = await load();
109
118
  if (!saved) return { ok: false, reason: 'missing', message: '本机还没有 Cindy 登录态' };
119
+ if (!validRealmMetadata(saved)) return invalidRealm();
110
120
 
111
121
  if (revision !== credentialRevision) return superseded();
112
122
  const refreshed = await refresh(saved);
113
123
  if (revision !== credentialRevision) return superseded();
114
124
  if (refreshed.ok) {
115
125
  const session = { ...saved, ...refreshed.session };
126
+ if (!validRealmMetadata(session)) return invalidRealm();
116
127
  return serializeWrite(async () => {
117
128
  const stored = await load();
118
129
  if (revision !== credentialRevision || !sameCredential(saved, stored)) return superseded();
@@ -155,9 +166,16 @@ export async function restoreSession(ports = {}) {
155
166
  */
156
167
  export async function adoptSession(session, ports = {}) {
157
168
  const save = ports.saveSession ?? saveSession;
169
+ const isCurrent = ports.isCurrent ?? (() => true);
170
+ const stale = () => Object.assign(new Error('Login superseded'), { code: 'LOGIN_SUPERSEDED' });
171
+ if (!isCurrent()) throw stale();
158
172
  const stored = { deviceId: session.deviceId ?? randomUUID(), ...session };
159
- credentialRevision += 1; // Fence refreshes immediately, before waiting for an older writer.
160
- await serializeWrite(() => save(stored));
173
+ const revision = ++credentialRevision; // Fence refreshes before waiting for an older writer.
174
+ await serializeWrite(async () => {
175
+ if (revision !== credentialRevision || !isCurrent()) throw stale();
176
+ await save(stored);
177
+ if (!isCurrent()) throw stale();
178
+ });
161
179
  return stored;
162
180
  }
163
181
 
@@ -0,0 +1,267 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { authError, authRegion, authJson, createAuthEndpointRegistry, CindyAuthError } from './cindy-auth-endpoints.js';
3
+ import { beginBrowserAuth } from './cindy-browser-auth.js';
4
+ import { validateIdentifier } from './cindy-login-flow.js';
5
+
6
+ const text = (value, max = 2048) => typeof value === 'string' && value.length > 0 && value.length <= max;
7
+ const protocols = ['oidc', 'saml', 'cas'];
8
+ const social = ['apple', 'google', 'wechat'];
9
+ const terminal = ['completed', 'cancelled', 'error'];
10
+ const mask = value => value?.includes('@') ? value.slice(0, 1) + '***@' + value.split('@')[1] : value ? '***' + value.slice(-4) : '';
11
+ function providersOf(value, region) {
12
+ if (!value || value.region !== region || typeof value.phone !== 'boolean' || typeof value.email !== 'boolean'
13
+ || !Array.isArray(value.social) || value.social.some(x => !social.includes(x))) throw authError('INVALID_PROVIDERS');
14
+ let captcha;
15
+ if (value.captcha) {
16
+ if (value.captcha.provider !== 'turnstile' || !text(value.captcha.siteKey) || !Array.isArray(value.captcha.requiredFor)) throw authError('INVALID_PROVIDERS');
17
+ captcha = { requiredFor: value.captcha.requiredFor.filter(x => ['email_request_code', 'phone_request_code'].includes(x)) };
18
+ }
19
+ return { region, phone: value.phone, email: value.email, social: [...value.social], ...(captcha ? { captcha } : {}) };
20
+ }
21
+ function methodsOf(items) {
22
+ if (!Array.isArray(items)) throw authError('INVALID_RESPONSE');
23
+ return items.flatMap(item => {
24
+ if (item?.type === 'email_code') return [{ type: 'email_code' }];
25
+ if (item?.type === 'sso') {
26
+ if (!text(item.connectionId, 256) || !protocols.includes(item.protocol) || !text(item.orgName, 300)
27
+ || typeof item.connectionName !== 'string' || typeof item.ssoRequired !== 'boolean') throw authError('INVALID_RESPONSE');
28
+ return [{ type: 'sso', connectionId: item.connectionId, protocol: item.protocol, orgName: item.orgName,
29
+ connectionName: item.connectionName.slice(0, 300), ssoRequired: item.ssoRequired }];
30
+ }
31
+ if (!text(item?.type)) throw authError('INVALID_RESPONSE');
32
+ return [];
33
+ });
34
+ }
35
+ function validContact(kind, identifier) {
36
+ const checked = validateIdentifier(kind, identifier);
37
+ if (!checked.ok || checked.value.length > 254) throw authError('INVALID_IDENTIFIER');
38
+ return kind === 'email' ? checked.value.toLowerCase() : checked.value;
39
+ }
40
+ function publicMember(member) {
41
+ if (!text(member?.id, 256) || typeof member.displayName !== 'string') throw authError('INVALID_RESPONSE');
42
+ return { id: member.id, displayName: member.displayName.slice(0, 300), orgName: typeof member.orgName === 'string' ? member.orgName.slice(0, 300) : null };
43
+ }
44
+
45
+ /** One installation-scoped owner. Tickets, codes and PKCE material never enter view(). */
46
+ export function createCindyAuthController({ deviceId, commitSession, registry = createAuthEndpointRegistry(),
47
+ fetchImpl = fetch, request: requestPort, browser = beginBrowserAuth, onStart = () => {}, now = Date.now, lifetimeMs = 15 * 60000 } = {}) {
48
+ const request = requestPort ?? ((endpoints, path, body, signal, timeoutMs) =>
49
+ authJson(endpoints.authApiBaseUrl + path, { body, signal, timeoutMs, fetchImpl }));
50
+ let active = null;
51
+ let epoch = 0;
52
+ let committing = Promise.resolve();
53
+ let disposed = false;
54
+ const current = attempt => !disposed && active === attempt && attempt.epoch === epoch && !attempt.abort.signal.aborted;
55
+ function cleanup(attempt) {
56
+ if (!attempt) return;
57
+ clearTimeout(attempt.timer); attempt.abort.abort(); attempt.browser?.close();
58
+ attempt.ticket = null; attempt.authorizationUrl = null;
59
+ }
60
+ function invalidate() { epoch++; cleanup(active); if (active) { active.step = 'cancelled'; active.busy = false; active.revision++; } }
61
+ function view(attempt = active) {
62
+ if (!attempt) return null;
63
+ if (current(attempt) && now() >= attempt.expiresAt && !attempt.sealed) { invalidate(); attempt.step = 'error'; attempt.error = 'LOGIN_EXPIRED'; }
64
+ return { attemptId: attempt.id, revision: attempt.revision, region: attempt.region, initialRegion: attempt.initialRegion,
65
+ step: attempt.step, busy: attempt.busy, providers: attempt.providers, methods: attempt.methods,
66
+ ...(attempt.pendingRegion ? { targetRegion: attempt.pendingRegion } : {}),
67
+ ...(attempt.accounts ? { accounts: attempt.accounts } : {}),
68
+ ...(attempt.kind ? { kind: attempt.kind } : {}),
69
+ ...(attempt.identifier ? { targetMasked: mask(attempt.identifier) } : {}),
70
+ ...(attempt.bindType ? { bindType: attempt.bindType } : {}),
71
+ ...(attempt.verification ? { channel: attempt.verification.channel, targetMasked: attempt.verification.targetMasked } : {}),
72
+ ...(attempt.authorizationUrl ? { authorizationUrl: attempt.authorizationUrl } : {}),
73
+ ...(attempt.challengeUrl ? { challengeUrl: attempt.challengeUrl } : {}),
74
+ ...(attempt.member ? { membership: attempt.member } : {}),
75
+ ...(attempt.error ? { error: attempt.error } : {}) };
76
+ }
77
+ function check(attempt) { if (!current(attempt) || now() >= attempt.expiresAt) throw authError('LOGIN_SUPERSEDED', 409); }
78
+ async function call(attempt, path, body, endpoints = attempt.endpoints) {
79
+ check(attempt); const value = await request(endpoints, path, body, attempt.abort.signal); check(attempt); return value;
80
+ }
81
+ async function load(attempt, region) {
82
+ const endpoints = await registry.load(region, attempt.abort.signal); check(attempt);
83
+ const providers = providersOf(await call(attempt, '/api/auth/providers', undefined, endpoints), region);
84
+ return { endpoints, providers };
85
+ }
86
+ async function accept(attempt, outcome) {
87
+ check(attempt);
88
+ if (!outcome || Boolean(outcome.accountToken) !== Boolean(outcome.accountRefreshToken)) throw authError('INVALID_RESPONSE');
89
+ attempt.ticket = null; attempt.accounts = null; attempt.bindType = null; attempt.bindingContact = null; attempt.verification = null; attempt.authorizationUrl = null;
90
+ if (outcome.status === 'select_account') {
91
+ if (!text(outcome.loginTicket) || !Array.isArray(outcome.accounts) || !outcome.accounts.length) throw authError('INVALID_RESPONSE');
92
+ attempt.ticket = outcome.loginTicket; attempt.accounts = outcome.accounts.map(publicMember); attempt.step = 'account-selection';
93
+ } else if (outcome.status === 'binding_required') {
94
+ if (!['phone', 'email'].includes(outcome.bindType) || !text(outcome.bindTicket)) throw authError('INVALID_RESPONSE');
95
+ attempt.ticket = outcome.bindTicket; attempt.bindType = outcome.bindType; attempt.step = 'binding';
96
+ } else if (outcome.status === 'sso_verification_required') {
97
+ if (!['email', 'sms'].includes(outcome.channel) || !text(outcome.verificationTicket) || !text(outcome.targetMasked, 300)) throw authError('INVALID_RESPONSE');
98
+ attempt.ticket = outcome.verificationTicket; attempt.verification = { channel: outcome.channel, targetMasked: outcome.targetMasked }; attempt.step = 'sso-verification';
99
+ } else if (outcome.status === 'ok') {
100
+ if (!text(outcome.accessToken, 100000) || !text(outcome.refreshToken, 100000)) throw authError('INVALID_RESPONSE');
101
+ const member = publicMember(outcome.membership);
102
+ attempt.step = 'committing'; attempt.sealed = true;
103
+ const lease = () => current(attempt);
104
+ committing = Promise.resolve().then(async () => {
105
+ check(attempt);
106
+ await commitSession({ sessionVersion: 2, realm: attempt.region, endpointSnapshot: attempt.endpoints,
107
+ authBaseUrl: attempt.endpoints.authApiBaseUrl, deviceId: attempt.deviceId, membershipId: member.id,
108
+ kind: attempt.kind ?? 'sso', identifier: attempt.identifier ?? member.displayName, clientType: 'desktop',
109
+ accessToken: outcome.accessToken, refreshToken: outcome.refreshToken }, lease);
110
+ check(attempt);
111
+ });
112
+ await committing;
113
+ attempt.member = member; attempt.step = 'completed'; cleanup(attempt);
114
+ } else throw authError('INVALID_RESPONSE');
115
+ }
116
+ async function discoverOrg(attempt, org) {
117
+ if (!text(org, 254) || /[\s/@]/.test(org)) throw authError('INVALID_ORGANIZATION');
118
+ const results = await Promise.allSettled(['cn', 'global'].map(async region => {
119
+ const endpoints = await registry.load(region, attempt.abort.signal); check(attempt);
120
+ const result = await call(attempt, '/api/auth/sso/discovery', { org: org.toLowerCase() }, endpoints);
121
+ if (result?.region !== region || typeof result.orgName !== 'string' || !Array.isArray(result.connections)) throw authError('INVALID_RESPONSE');
122
+ if (!result.connections.length) throw authError('ORG_SSO_NOT_FOUND');
123
+ const methods = methodsOf(result.connections.map(connection => ({ ...connection, type: 'sso', orgName: result.orgName, ssoRequired: true })));
124
+ return { region, methods };
125
+ }));
126
+ check(attempt);
127
+ if (results.every(r => r.status === 'fulfilled')) throw authError('ORG_REALM_AMBIGUOUS');
128
+ const successes = results.filter(r => r.status === 'fulfilled');
129
+ const missing = results.filter(r => r.status === 'rejected' && r.reason?.code === 'ORG_SSO_NOT_FOUND');
130
+ if (successes.length === 1 && missing.length === 1) return successes[0].value;
131
+ if (missing.length === 2) throw authError('ORG_SSO_NOT_FOUND');
132
+ throw authError('ORG_REALM_UNAVAILABLE', 503);
133
+ }
134
+ function showMethods(attempt, found) {
135
+ attempt.methods = found.methods;
136
+ if (found.region !== attempt.region) { attempt.pendingRegion = found.region; attempt.step = 'region-confirmation'; }
137
+ else attempt.step = 'method-choice';
138
+ }
139
+ async function sendCode(attempt, kind, identifier, captchaToken) {
140
+ if (!attempt.providers[kind]) throw authError('LOGIN_METHOD_DISABLED');
141
+ if (attempt.providers.captcha?.requiredFor.includes(kind + '_request_code') && !captchaToken) {
142
+ attempt.pendingCode = { kind, identifier }; attempt.step = 'captcha';
143
+ const url = new URL(attempt.endpoints.authApiBaseUrl + '/captcha/turnstile');
144
+ url.search = new URLSearchParams({ action: kind + '_request_code', theme: 'auto', lang: 'zh-CN' }).toString();
145
+ attempt.challengeUrl = url.href; return;
146
+ }
147
+ const result = await call(attempt, `/api/auth/${kind}/request-code`, { [kind]: identifier, locale: 'zh-CN', ...(captchaToken ? { captchaToken } : {}) });
148
+ if (result?.status !== 'sent') throw authError('INVALID_RESPONSE');
149
+ attempt.kind = kind; attempt.identifier = identifier; attempt.challengeUrl = null; attempt.pendingCode = null; attempt.step = 'verification-code';
150
+ }
151
+ async function work(attempt, input) {
152
+ const action = input.action;
153
+ if (action === 'discover_org' || action === 'discover_email') {
154
+ if (!['identifier', 'method-choice'].includes(attempt.step)) throw authError('INVALID_STEP', 409);
155
+ if (action === 'discover_org') showMethods(attempt, await discoverOrg(attempt, String(input.org ?? '').trim()));
156
+ else {
157
+ const email = validContact('email', input.identifier); attempt.personalEmail = email;
158
+ let org = null;
159
+ try { org = await discoverOrg(attempt, email.split('@')[1]); } catch (error) { if (error.code !== 'ORG_SSO_NOT_FOUND') throw error; }
160
+ if (org && org.region !== attempt.initialRegion) showMethods(attempt, { ...org, methods: [...org.methods, { type: 'email_code' }] });
161
+ else {
162
+ const result = await call(attempt, '/api/auth/discovery', { email });
163
+ const methods = methodsOf(result?.methods);
164
+ if (!methods.length) throw authError('LOGIN_METHOD_DISABLED');
165
+ showMethods(attempt, { region: attempt.region, methods });
166
+ }
167
+ }
168
+ } else if (action === 'confirm_region') {
169
+ if (attempt.step !== 'region-confirmation' || !attempt.pendingRegion) throw authError('INVALID_STEP', 409);
170
+ const next = await load(attempt, attempt.pendingRegion);
171
+ attempt.region = attempt.pendingRegion; attempt.pendingRegion = null; Object.assign(attempt, next); attempt.step = 'method-choice';
172
+ } else if (action === 'personal_email') {
173
+ if (!attempt.personalEmail || !attempt.methods?.some(x => x.type === 'email_code')) throw authError('INVALID_STEP');
174
+ Object.assign(attempt, await load(attempt, attempt.initialRegion)); attempt.region = attempt.initialRegion; attempt.pendingRegion = null; attempt.methods = [];
175
+ await sendCode(attempt, 'email', attempt.personalEmail);
176
+ } else if (action === 'request_code') {
177
+ if (!['identifier', 'verification-code'].includes(attempt.step)) throw authError('INVALID_STEP');
178
+ await sendCode(attempt, input.kind, validContact(input.kind, input.identifier));
179
+ } else if (action === 'captcha_complete') {
180
+ if (attempt.step !== 'captcha' || !attempt.pendingCode) throw authError('INVALID_STEP');
181
+ let url; try { url = new URL(input.resultUrl); } catch { throw authError('INVALID_CAPTCHA_RESULT'); }
182
+ if (url.origin !== new URL(attempt.endpoints.authApiBaseUrl).origin || url.pathname !== '/captcha/turnstile' || !url.hash.startsWith('#cindy-captcha=ok.')) throw authError('INVALID_CAPTCHA_RESULT');
183
+ let token; try { token = decodeURIComponent(url.hash.slice('#cindy-captcha=ok.'.length)); } catch { throw authError('INVALID_CAPTCHA_RESULT'); }
184
+ if (!text(token, 8192)) throw authError('INVALID_CAPTCHA_RESULT');
185
+ await sendCode(attempt, attempt.pendingCode.kind, attempt.pendingCode.identifier, token);
186
+ } else if (action === 'verify_code') {
187
+ if (attempt.step !== 'verification-code' || !text(input.code, 100)) throw authError('INVALID_STEP');
188
+ await accept(attempt, await call(attempt, `/api/auth/${attempt.kind}/verify-code`, { [attempt.kind]: attempt.identifier, code: input.code.trim(), deviceId: attempt.deviceId, clientType: 'desktop', locale: 'zh-CN' }));
189
+ } else if (action === 'select_account') {
190
+ if (attempt.step !== 'account-selection' || !attempt.accounts.some(x => x.id === input.accountId)) throw authError('INVALID_ACCOUNT');
191
+ await accept(attempt, await call(attempt, '/api/auth/select-account', { loginTicket: attempt.ticket, accountId: input.accountId, deviceId: attempt.deviceId }));
192
+ } else if (action === 'binding_request' || action === 'binding_verify') {
193
+ if (attempt.step !== 'binding') throw authError('INVALID_STEP');
194
+ const contact = validContact(attempt.bindType, input.identifier);
195
+ const body = { bindTicket: attempt.ticket, [attempt.bindType]: contact };
196
+ if (action === 'binding_request') {
197
+ const response = await call(attempt, '/api/auth/binding/request-code', { ...body, locale: 'zh-CN' });
198
+ if (response?.status !== 'sent') throw authError('INVALID_RESPONSE');
199
+ attempt.bindingContact = contact;
200
+ } else {
201
+ if (contact !== attempt.bindingContact || !text(input.code, 100)) throw authError('INVALID_STEP');
202
+ await accept(attempt, await call(attempt, '/api/auth/binding/verify', { ...body, code: input.code.trim(), deviceId: attempt.deviceId }));
203
+ }
204
+ } else if (action === 'sso_request' || action === 'sso_verify') {
205
+ if (attempt.step !== 'sso-verification') throw authError('INVALID_STEP');
206
+ if (action === 'sso_request') {
207
+ const response = await call(attempt, '/api/auth/sso/verification/request-code', { verificationTicket: attempt.ticket, deviceId: attempt.deviceId });
208
+ if (response?.status !== 'sent') throw authError('INVALID_RESPONSE');
209
+ } else {
210
+ if (!text(input.code, 100)) throw authError('INVALID_CODE');
211
+ await accept(attempt, await call(attempt, '/api/auth/sso/verification/verify', { verificationTicket: attempt.ticket, code: input.code.trim(), deviceId: attempt.deviceId }));
212
+ }
213
+ } else if (action === 'start_browser') {
214
+ if (!['identifier', 'method-choice'].includes(attempt.step)) throw authError('INVALID_STEP');
215
+ if (input.kind === 'social') { if (!attempt.providers.social.includes(input.providerOrConnectionId)) throw authError('LOGIN_METHOD_DISABLED'); }
216
+ else if (input.kind !== 'sso' || !attempt.methods?.some(x => x.type === 'sso' && x.connectionId === input.providerOrConnectionId)) throw authError('CONNECTION_NOT_FOUND');
217
+ attempt.kind = input.kind === 'social' ? input.providerOrConnectionId : 'sso';
218
+ const started = await browser({ endpoints: attempt.endpoints, kind: input.kind, providerOrConnectionId: input.providerOrConnectionId,
219
+ deviceId: attempt.deviceId, request, signal: attempt.abort.signal });
220
+ check(attempt); attempt.browser = started; attempt.authorizationUrl = started.authorizationUrl; attempt.step = 'browser';
221
+ attempt.background = started.result.then(async outcome => { check(attempt); await accept(attempt, outcome); }).catch(error => {
222
+ if (current(attempt)) { attempt.error = error instanceof CindyAuthError ? error.code : 'AUTH_REQUEST_FAILED'; attempt.step = 'error'; cleanup(attempt); }
223
+ }).finally(() => { if (active === attempt) { attempt.busy = false; attempt.revision++; } });
224
+ } else throw authError('UNKNOWN_LOGIN_ACTION');
225
+ }
226
+ async function command(input = {}) {
227
+ let startedId = null;
228
+ try {
229
+ if (disposed) throw authError('LOGIN_UNAVAILABLE', 503);
230
+ if (input.action === 'start') {
231
+ if (active && !terminal.includes(active.step) && !input.takeover) throw authError('LOGIN_BUSY', 409);
232
+ if (active?.sealed && active.step === 'committing') throw authError('LOGIN_COMMITTING', 409);
233
+ const region = authRegion(input.region);
234
+ invalidate(); onStart();
235
+ const attempt = { id: randomUUID(), epoch, region, initialRegion: region, revision: 0, step: 'identifier',
236
+ busy: true, abort: new AbortController(), expiresAt: now() + lifetimeMs, methods: [], providers: null };
237
+ active = attempt; startedId = attempt.id;
238
+ attempt.timer = setTimeout(() => { if (current(attempt) && !attempt.sealed) { invalidate(); attempt.step = 'error'; attempt.error = 'LOGIN_EXPIRED'; } }, lifetimeMs); attempt.timer.unref?.();
239
+ try { attempt.deviceId = await deviceId(); check(attempt); Object.assign(attempt, await load(attempt, region)); }
240
+ catch (error) { if (active === attempt) { attempt.step = 'error'; cleanup(attempt); } throw error; }
241
+ finally { attempt.busy = false; attempt.revision++; }
242
+ return { ok: true, view: view() };
243
+ }
244
+ const attempt = active;
245
+ if (!attempt || input.attemptId !== attempt.id) throw authError('LOGIN_SUPERSEDED', 409);
246
+ if (input.action === 'read') return { ok: true, view: view() };
247
+ if (input.action === 'cancel') {
248
+ if (attempt.sealed) throw authError('LOGIN_COMMITTING', 409);
249
+ invalidate(); return { ok: true, view: view() };
250
+ }
251
+ check(attempt);
252
+ if (input.revision !== attempt.revision || attempt.busy) throw authError('LOGIN_STEP_CHANGED', 409);
253
+ attempt.busy = true; attempt.error = null; attempt.revision++;
254
+ try { await work(attempt, input); } catch (error) {
255
+ if (current(attempt) && attempt.step === 'committing') { attempt.step = 'error'; attempt.error = 'CREDENTIAL_COMMIT_FAILED'; cleanup(attempt); }
256
+ throw error;
257
+ } finally { if (active === attempt) { attempt.busy = false; attempt.revision++; } }
258
+ return { ok: true, view: view() };
259
+ } catch (error) {
260
+ return { ok: false, code: error instanceof CindyAuthError ? error.code : 'AUTH_REQUEST_FAILED',
261
+ statusCode: error instanceof CindyAuthError ? error.status : 502, ...(input.attemptId === active?.id || startedId === active?.id ? { view: view() } : {}) };
262
+ }
263
+ }
264
+ async function stop() { invalidate(); await committing.catch(() => {}); }
265
+ async function dispose() { disposed = true; await stop(); }
266
+ return { command, stop, dispose };
267
+ }
@@ -0,0 +1,85 @@
1
+ /** Trusted regional bootstrap, from Cindy config/endpoint{,.global}.json. */
2
+ export const AUTH_MANIFESTS = Object.freeze({
3
+ cn: 'https://hotfix.cindy.com.cn/cindy/endpoint.json',
4
+ global: 'https://hotfix.cindy.app/cindy/endpoint.json',
5
+ });
6
+ export class CindyAuthError extends Error {
7
+ constructor(code, status = 400) { super(code); this.code = code; this.status = status; }
8
+ }
9
+ export const authError = (code, status) => new CindyAuthError(code, status);
10
+ export function authRegion(value) {
11
+ if (value !== 'cn' && value !== 'global') throw authError('INVALID_REGION');
12
+ return value;
13
+ }
14
+ const nonempty = value => typeof value === 'string' && value.length > 0;
15
+ function trustedUrl(value, region, optional = false) {
16
+ if (optional && (value === undefined || value === '')) return '';
17
+ if (!nonempty(value)) throw authError('INVALID_ENDPOINT_MANIFEST');
18
+ let url; try { url = new URL(value); } catch { throw authError('INVALID_ENDPOINT_MANIFEST'); }
19
+ const domain = region === 'cn' ? 'cindy.com.cn' : 'cindy.app';
20
+ if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash || url.port
21
+ || !(url.hostname === domain || url.hostname.endsWith('.' + domain))) throw authError('INVALID_ENDPOINT_MANIFEST');
22
+ return url.href.replace(/\/$/, '');
23
+ }
24
+ export function parseAuthEndpoints(manifest, region) {
25
+ authRegion(region);
26
+ if (!manifest || manifest.schemaVersion !== 1 || (manifest.region !== undefined && manifest.region !== region)) throw authError('INVALID_ENDPOINT_MANIFEST');
27
+ const authApiBaseUrl = trustedUrl(manifest.authApiBaseUrl, region);
28
+ const deviceLinkApiBaseUrl = trustedUrl(manifest.deviceLinkApiBaseUrl, region);
29
+ const authDesktopCallbackUrl = trustedUrl(manifest.authDesktopCallbackUrl, region, true);
30
+ if (authDesktopCallbackUrl && new URL(authDesktopCallbackUrl).origin !== new URL(authApiBaseUrl).origin) throw authError('INVALID_ENDPOINT_MANIFEST');
31
+ return Object.freeze({ schemaVersion: 1, region, authApiBaseUrl, deviceLinkApiBaseUrl, authDesktopCallbackUrl });
32
+ }
33
+
34
+ /** Fixed error text/codes only: never put upstream bodies, URLs or credentials into errors. */
35
+ export async function authJson(url, { body, signal, fetchImpl = fetch, timeoutMs = 15000 } = {}) {
36
+ const timeout = AbortSignal.timeout(timeoutMs);
37
+ const combined = signal ? AbortSignal.any([signal, timeout]) : timeout;
38
+ try {
39
+ const response = await fetchImpl(url, { method: body === undefined ? 'GET' : 'POST',
40
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
41
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: combined, redirect: 'error' });
42
+ const text = await response.text();
43
+ if (text.length > 256 * 1024) throw authError('INVALID_RESPONSE');
44
+ let data; try { data = JSON.parse(text); } catch { throw authError('INVALID_RESPONSE'); }
45
+ if (!response.ok) {
46
+ const raw = data?.error?.code ?? data?.code;
47
+ const known = new Set(['ORG_SSO_NOT_FOUND', 'INVALID_AUTH_CODE', 'INVALID_CODE', 'CODE_EXPIRED',
48
+ 'CAPTCHA_REQUIRED', 'CAPTCHA_INVALID', 'CAPTCHA_FAILED', 'RATE_LIMITED', 'CONNECTION_NOT_FOUND',
49
+ 'INVALID_LOGIN_TICKET', 'INVALID_BIND_TICKET', 'INVALID_SSO_VERIFICATION_TICKET', 'SSO_DISABLED', 'ACCOUNT_DISABLED']);
50
+ throw authError(known.has(raw) ? raw : 'AUTH_REQUEST_FAILED', response.status);
51
+ }
52
+ return data;
53
+ } catch (error) {
54
+ if (signal?.aborted) throw authError('USER_CANCELLED');
55
+ if (timeout.aborted) throw authError('REQUEST_TIMEOUT');
56
+ if (error instanceof CindyAuthError) throw error;
57
+ throw authError('NETWORK_ERROR', 502);
58
+ }
59
+ }
60
+ export function createAuthEndpointRegistry({ fetchImpl = fetch } = {}) {
61
+ return { async load(region, signal) {
62
+ authRegion(region);
63
+ return parseAuthEndpoints(await authJson(AUTH_MANIFESTS[region], { fetchImpl, signal }), region);
64
+ } };
65
+ }
66
+ export function relayForEndpoints(endpoints) {
67
+ return endpoints.deviceLinkApiBaseUrl.replace(/^https:/, 'wss:') + '/api/device-link/ws';
68
+ }
69
+ /** Migration only: pre-v2 sessions knew just these official auth origins. New logins use manifests. */
70
+ export function sessionEndpoints(session) {
71
+ if (!session) return null;
72
+ if (session.endpointSnapshot) return validateSessionEndpoints(session);
73
+ const origins = { 'https://auth.cindy.com.cn': ['cn', 'https://device-link.cindy.com.cn'],
74
+ 'https://auth.cindy.app': ['global', 'https://device-link.cindy.app'] };
75
+ const legacy = origins[session.authBaseUrl?.replace(/\/$/, '')];
76
+ if (!legacy || (session.realm !== undefined && session.realm !== legacy[0]) || session.sessionVersion === 2) throw authError('SESSION_REALM_MISMATCH');
77
+ return parseAuthEndpoints({ schemaVersion: 1, authApiBaseUrl: session.authBaseUrl.replace(/\/$/, ''), deviceLinkApiBaseUrl: legacy[1] }, legacy[0]);
78
+ }
79
+
80
+ export function validateSessionEndpoints(session) {
81
+ if (!session?.endpointSnapshot) return null;
82
+ const endpoints = parseAuthEndpoints(session.endpointSnapshot, authRegion(session.realm));
83
+ if (endpoints.authApiBaseUrl !== session.authBaseUrl) throw authError('SESSION_REALM_MISMATCH');
84
+ return endpoints;
85
+ }
@@ -0,0 +1,104 @@
1
+ import { randomBytes, createHash } from 'node:crypto';
2
+ import { createServer } from 'node:http';
3
+ import { authError } from './cindy-auth-endpoints.js';
4
+
5
+ const secret = () => randomBytes(32).toString('base64url');
6
+ const hash = value => createHash('sha256').update(value).digest('base64url');
7
+ function delay(ms, signal) {
8
+ return new Promise(resolve => {
9
+ const done = () => { clearTimeout(timer); signal.removeEventListener('abort', done); resolve(); };
10
+ const timer = setTimeout(done, ms); timer.unref?.();
11
+ signal.addEventListener('abort', done, { once: true });
12
+ if (signal.aborted) done();
13
+ });
14
+ }
15
+
16
+ /** Public authorize URL carries a hash/challenge only. All secret originals remain here. */
17
+ export async function beginBrowserAuth({ endpoints, kind, providerOrConnectionId, deviceId, request,
18
+ signal, timeoutMs = 300000, pollDelayMs = 1000 }) {
19
+ const codeVerifier = secret();
20
+ const codeChallenge = hash(codeVerifier);
21
+ const deadline = AbortSignal.timeout(timeoutMs);
22
+ const active = signal ? AbortSignal.any([signal, deadline]) : deadline;
23
+ let close = () => {};
24
+ let authorizationUrl;
25
+ function urlFor(redirectUri, state) {
26
+ const segment = kind === 'social' ? 'social' : 'sso';
27
+ const url = new URL(endpoints.authApiBaseUrl + `/api/auth/${segment}/${encodeURIComponent(providerOrConnectionId)}/authorize`);
28
+ url.search = new URLSearchParams({ client_type: 'desktop', device_id: deviceId, redirect_uri: redirectUri,
29
+ code_challenge: codeChallenge, code_challenge_method: 'S256', client_state: state, ui_locale: 'zh-CN' }).toString();
30
+ return url.href;
31
+ }
32
+ let callback;
33
+ if (endpoints.authDesktopCallbackUrl) {
34
+ const pollSecret = secret();
35
+ authorizationUrl = urlFor(endpoints.authDesktopCallbackUrl, hash(pollSecret));
36
+ callback = (async () => {
37
+ let failures = 0;
38
+ const started = Date.now();
39
+ while (!active.aborted) {
40
+ try {
41
+ const result = await request(endpoints, '/api/auth/desktop/callback/poll', { pollSecret, deviceId }, active, 30000);
42
+ failures = 0;
43
+ if (result?.status === 'ok' && typeof result.code === 'string' && result.code) return result.code;
44
+ if (result?.status === 'expired') throw authError('INVALID_AUTH_CODE');
45
+ if (result?.status === 'error') throw authError('AUTH_PROVIDER_FAILED');
46
+ if (result?.status !== 'pending') throw authError('INVALID_RESPONSE');
47
+ } catch (error) {
48
+ if (active.aborted || !['NETWORK_ERROR', 'REQUEST_TIMEOUT', 'AUTH_REQUEST_FAILED'].includes(error.code) || ++failures >= 8) throw error;
49
+ }
50
+ await delay(Date.now() - started >= 30000 ? Math.max(pollDelayMs, 2000) : pollDelayMs, active);
51
+ }
52
+ throw authError('USER_CANCELLED');
53
+ })();
54
+ } else {
55
+ const state = secret();
56
+ let resolveCallback;
57
+ let rejectCallback;
58
+ callback = new Promise((resolve, reject) => { resolveCallback = resolve; rejectCallback = reject; });
59
+ // Attach immediately: bind/listen may fail before the final result chain is returned.
60
+ callback.catch(() => {});
61
+ let consumed = false;
62
+ const server = createServer((req, res) => {
63
+ let url;
64
+ try {
65
+ if (typeof req.url !== 'string' || req.url.length > 16384) throw authError('INVALID_AUTH_CODE');
66
+ url = new URL(req.url, 'http://127.0.0.1');
67
+ } catch { res.writeHead(400, { 'cache-control': 'no-store' }).end('Invalid callback'); return; }
68
+ if (consumed || req.method !== 'GET' || url.pathname !== '/auth/callback'
69
+ || url.searchParams.getAll('state').length !== 1 || url.searchParams.get('state') !== state
70
+ || (url.searchParams.getAll('code').length !== 1 && !url.searchParams.has('error'))) {
71
+ res.writeHead(400, { 'cache-control': 'no-store' }).end('Invalid callback'); return;
72
+ }
73
+ consumed = true;
74
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store',
75
+ 'referrer-policy': 'no-referrer', 'content-security-policy': "default-src 'none'; frame-ancestors 'none'" })
76
+ .end('<!doctype html><meta charset="utf-8"><title>Cindy</title><p>Return to DSH to complete sign-in. 请返回 DSH 完成登录。</p>');
77
+ if (url.searchParams.has('error')) rejectCallback(authError('AUTH_PROVIDER_FAILED'));
78
+ else if (!url.searchParams.get('code')) rejectCallback(authError('INVALID_AUTH_CODE'));
79
+ else resolveCallback(url.searchParams.get('code'));
80
+ server.close();
81
+ });
82
+ close = () => { server.close(); server.closeAllConnections?.(); };
83
+ const cancel = () => { close(); rejectCallback(authError('USER_CANCELLED')); };
84
+ active.addEventListener('abort', cancel, { once: true });
85
+ const closeServer = close;
86
+ close = () => { active.removeEventListener('abort', cancel); closeServer(); };
87
+ try {
88
+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
89
+ if (active.aborted) throw authError('USER_CANCELLED');
90
+ authorizationUrl = urlFor(`http://127.0.0.1:${server.address().port}/auth/callback`, state);
91
+ } catch (error) { close(); throw error; }
92
+ }
93
+ const result = callback.then(async code => {
94
+ if (active.aborted) throw authError('USER_CANCELLED');
95
+ const outcome = await request(endpoints, '/api/auth/token', { grantType: 'authorization_code', code, codeVerifier, deviceId }, active);
96
+ if (active.aborted) throw authError('USER_CANCELLED');
97
+ return outcome;
98
+ }).catch(error => {
99
+ if (deadline.aborted && !signal?.aborted) throw authError('REQUEST_TIMEOUT');
100
+ throw error;
101
+ }).finally(close);
102
+ result.catch(() => {});
103
+ return { authorizationUrl, result, close };
104
+ }