opencode-next 0.0.0-stage → 1.0.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.
@@ -0,0 +1,321 @@
1
+ /**
2
+ * OpenCode Go 獨立憑證解析模組(Stage 1)。
3
+ *
4
+ * 設計界線:
5
+ * - 僅解析 OpenCode Console Personal API Key,不沿用免費通道的 OAuth token (`st_*`) 或 `org_id`。
6
+ * - 不自動匯入其他外掛的憑證,也不讀取 `opencode.db`、`auth.json` 或 `opencode-next.*.json`。
7
+ * - 優先嘗試 DSH 安全憑證服務(`ctx.get('credentials')` / `ctx.credentials`),不適用時退回環境變數。
8
+ * - 絕不把明文 key 寫入一般設定、狀態 API、錯誤訊息或日誌。
9
+ */
10
+
11
+ import { createHash } from 'node:crypto';
12
+ import { GO_CREDENTIAL_ENV_VAR } from '../constants.js';
13
+
14
+ const SAFE_REF_RE = /^[A-Za-z_][A-Za-z0-9_.:/-]{0,127}$/;
15
+ const RAW_SECRET_PREFIX_RE = /^(?:sk[-_]|oc[_-]|st_|bearer\s+)/i;
16
+
17
+ /**
18
+ * 檢查設定中的憑證參照名稱是否合法。
19
+ * 拒絕看起來像真實 API key 或含有空白的值,避免使用者把明文 key 貼進設定檔。
20
+ */
21
+ export function validateCredentialRef(rawRef) {
22
+ const ref = typeof rawRef === 'string' ? rawRef.trim() : '';
23
+ if (!ref) {
24
+ return {
25
+ valid: false,
26
+ reason: 'invalid-credential-ref',
27
+ message: 'Go credential reference is empty.'
28
+ };
29
+ }
30
+ if (RAW_SECRET_PREFIX_RE.test(ref) || /\s/.test(ref) || !SAFE_REF_RE.test(ref)) {
31
+ return {
32
+ valid: false,
33
+ reason: 'invalid-credential-ref',
34
+ message: 'Invalid Go credential reference; store only a reference name, not a raw API key.'
35
+ };
36
+ }
37
+ return { valid: true, ref };
38
+ }
39
+
40
+ /**
41
+ * 產生不可逆的 key 指紋,供快取隔離與換 key 偵測使用。
42
+ * 絕不回傳明文內容或可用於還原的片段。
43
+ */
44
+ export function fingerprintSecret(secret) {
45
+ if (typeof secret !== 'string' || secret.length === 0) return null;
46
+ return createHash('sha256').update(secret).digest('hex').slice(0, 16);
47
+ }
48
+
49
+ /**
50
+ * 從錯誤訊息或日誌字串移除任何可能外洩的密鑰與 Bearer 權杖。
51
+ */
52
+ export function redactSecret(text, secret = '') {
53
+ if (typeof text !== 'string' || text.length === 0) return '';
54
+ let sanitized = text;
55
+ if (typeof secret === 'string' && secret.length >= 4) {
56
+ sanitized = sanitized.split(secret).join('[REDACTED]');
57
+ }
58
+ sanitized = sanitized.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi, 'Bearer [REDACTED]');
59
+ sanitized = sanitized.replace(/\b(?:oc_[A-Za-z0-9_-]{6,}|sk-[A-Za-z0-9_-]{6,}|st_[A-Za-z0-9._-]{6,})\b/g, '[REDACTED]');
60
+ return sanitized;
61
+ }
62
+
63
+ function extractResolvedSecret(hit) {
64
+ if (typeof hit === 'string') return hit.trim();
65
+ if (hit && typeof hit === 'object') {
66
+ const raw = hit.value ?? hit.secret ?? hit.token ?? hit.apiKey ?? '';
67
+ return typeof raw === 'string' ? raw.trim() : '';
68
+ }
69
+ return '';
70
+ }
71
+
72
+ function getDshCredentialService(ctx) {
73
+ if (!ctx || typeof ctx !== 'object') return null;
74
+ try {
75
+ const fromGet = typeof ctx.get === 'function' ? ctx.get('credentials') : null;
76
+ const service = fromGet ?? ctx.credentials ?? null;
77
+ if (service && typeof service === 'object') return service;
78
+ } catch {
79
+ // 宿主未掛載安全憑證服務時安全退回環境變數。
80
+ }
81
+ return null;
82
+ }
83
+
84
+ export function getDshCredentialCapabilities(ctx) {
85
+ const service = getDshCredentialService(ctx);
86
+ return {
87
+ service,
88
+ canResolve: Boolean(service && typeof service.resolve === 'function'),
89
+ canSet: Boolean(service && typeof service.set === 'function'),
90
+ canUnset: Boolean(service && typeof service.unset === 'function'),
91
+ canDescribe: Boolean(service && typeof service.describe === 'function')
92
+ };
93
+ }
94
+
95
+ function buildKeyResult({ key, source, ref, dshCredentialsAvailable, canSave = false, canClear = false }) {
96
+ // 嚴格隔離:若誤填入 OAuth token(st_*),拒絕在 Go 通道使用,且不回顯內容。
97
+ if (key.startsWith('st_')) {
98
+ return {
99
+ present: false,
100
+ key: null,
101
+ source,
102
+ ref,
103
+ fingerprint: null,
104
+ dshCredentialsAvailable,
105
+ canSave,
106
+ canClear,
107
+ error: 'invalid-credential-type',
108
+ message: 'OpenCode Go requires an OpenCode Console Personal API Key, not an OAuth token.'
109
+ };
110
+ }
111
+ return {
112
+ present: true,
113
+ key,
114
+ source,
115
+ ref,
116
+ fingerprint: fingerprintSecret(key),
117
+ dshCredentialsAvailable,
118
+ canSave,
119
+ canClear,
120
+ error: null,
121
+ message: null
122
+ };
123
+ }
124
+
125
+ /**
126
+ * 解析 OpenCode Go 憑證:
127
+ * 1. 若 DSH 提供 `credentials` 服務且可解析 `ref`,優先採用;
128
+ * 2. 否則退回讀取環境變數(預設 `OPENCODE_GO_API_KEY`)。
129
+ */
130
+ export async function resolveGoCredential({
131
+ ctx = null,
132
+ credentialRef = GO_CREDENTIAL_ENV_VAR,
133
+ env = process.env
134
+ } = {}) {
135
+ const checkedRef = validateCredentialRef(credentialRef || GO_CREDENTIAL_ENV_VAR);
136
+ if (!checkedRef.valid) {
137
+ return {
138
+ present: false,
139
+ key: null,
140
+ source: null,
141
+ ref: null,
142
+ fingerprint: null,
143
+ dshCredentialsAvailable: false,
144
+ canSave: false,
145
+ canClear: false,
146
+ error: checkedRef.reason,
147
+ message: checkedRef.message
148
+ };
149
+ }
150
+
151
+ const ref = checkedRef.ref;
152
+ const { service, canResolve, canSet, canUnset, canDescribe } = getDshCredentialCapabilities(ctx);
153
+ const dshCredentialsAvailable = canResolve;
154
+
155
+ if (canDescribe) {
156
+ try {
157
+ await service.describe(ref);
158
+ } catch {
159
+ // describe 失敗不阻斷後續 resolve 或環境變數退路。
160
+ }
161
+ }
162
+
163
+ if (canResolve) {
164
+ try {
165
+ const hit = await service.resolve(ref);
166
+ const key = extractResolvedSecret(hit);
167
+ if (key) {
168
+ return buildKeyResult({
169
+ key,
170
+ source: 'dsh-credentials',
171
+ ref,
172
+ dshCredentialsAvailable,
173
+ canSave: canSet,
174
+ canClear: canUnset
175
+ });
176
+ }
177
+ } catch (err) {
178
+ return {
179
+ present: false,
180
+ key: null,
181
+ source: 'dsh-credentials',
182
+ ref,
183
+ fingerprint: null,
184
+ dshCredentialsAvailable,
185
+ canSave: canSet,
186
+ canClear: canUnset,
187
+ error: 'credential-resolve-failed',
188
+ message: redactSecret(err?.message || 'Could not resolve credential from DSH credential service.')
189
+ };
190
+ }
191
+ }
192
+
193
+ const envValue = env && typeof env === 'object' ? env[ref] : undefined;
194
+ const envKey = typeof envValue === 'string' ? envValue.trim() : '';
195
+ if (envKey) {
196
+ return buildKeyResult({
197
+ key: envKey,
198
+ source: 'env',
199
+ ref,
200
+ dshCredentialsAvailable,
201
+ canSave: canSet,
202
+ canClear: canUnset
203
+ });
204
+ }
205
+
206
+ return {
207
+ present: false,
208
+ key: null,
209
+ source: null,
210
+ ref,
211
+ fingerprint: null,
212
+ dshCredentialsAvailable,
213
+ canSave: canSet,
214
+ canClear: canUnset,
215
+ error: null,
216
+ message: null
217
+ };
218
+ }
219
+
220
+ /**
221
+ * 透過 DSH 安全憑證服務儲存 OpenCode Go API key。
222
+ * 絕不將明文 key 寫入一般設定、cordis 或外掛 JSON 檔案。
223
+ */
224
+ export async function saveGoCredential({
225
+ ctx = null,
226
+ credentialRef = GO_CREDENTIAL_ENV_VAR,
227
+ key
228
+ } = {}) {
229
+ const checkedRef = validateCredentialRef(credentialRef || GO_CREDENTIAL_ENV_VAR);
230
+ if (!checkedRef.valid) {
231
+ return { ok: false, error: checkedRef.reason, message: checkedRef.message };
232
+ }
233
+
234
+ const { service, canSet } = getDshCredentialCapabilities(ctx);
235
+ if (!canSet) {
236
+ return {
237
+ ok: false,
238
+ error: 'credentials_write_unavailable',
239
+ message: 'DSH credential service (credentials.set) is unavailable in this process; API key was not saved.'
240
+ };
241
+ }
242
+
243
+ const trimmed = typeof key === 'string' ? key.trim() : '';
244
+ if (!trimmed) {
245
+ return {
246
+ ok: false,
247
+ error: 'empty_key',
248
+ message: 'OpenCode Go API key cannot be empty.'
249
+ };
250
+ }
251
+ if (trimmed.startsWith('st_')) {
252
+ return {
253
+ ok: false,
254
+ error: 'invalid_credential_type',
255
+ message: 'OpenCode Go requires an OpenCode Console Personal API Key, not an OAuth token.'
256
+ };
257
+ }
258
+
259
+ try {
260
+ await service.set(checkedRef.ref, trimmed);
261
+ return { ok: true, ref: checkedRef.ref, source: 'dsh-credentials' };
262
+ } catch (err) {
263
+ return {
264
+ ok: false,
265
+ error: 'credential_save_failed',
266
+ message: redactSecret(err?.message || 'Could not save OpenCode Go API key.', trimmed)
267
+ };
268
+ }
269
+ }
270
+
271
+ /**
272
+ * 透過 DSH 安全憑證服務移除已儲存的 OpenCode Go API key。
273
+ */
274
+ export async function clearGoCredential({
275
+ ctx = null,
276
+ credentialRef = GO_CREDENTIAL_ENV_VAR
277
+ } = {}) {
278
+ const checkedRef = validateCredentialRef(credentialRef || GO_CREDENTIAL_ENV_VAR);
279
+ if (!checkedRef.valid) {
280
+ return { ok: false, error: checkedRef.reason, message: checkedRef.message };
281
+ }
282
+
283
+ const { service, canUnset } = getDshCredentialCapabilities(ctx);
284
+ if (!canUnset) {
285
+ return {
286
+ ok: false,
287
+ error: 'credentials_clear_unavailable',
288
+ message: 'DSH credential service (credentials.unset) is unavailable in this process.'
289
+ };
290
+ }
291
+
292
+ try {
293
+ await service.unset(checkedRef.ref);
294
+ return { ok: true, ref: checkedRef.ref };
295
+ } catch (err) {
296
+ return {
297
+ ok: false,
298
+ error: 'credential_clear_failed',
299
+ message: redactSecret(err?.message || 'Could not clear OpenCode Go API key.')
300
+ };
301
+ }
302
+ }
303
+
304
+ /**
305
+ * 產生可安全回傳給設定頁/狀態 API 的憑證摘要(絕不含密鑰本體或片段)。
306
+ */
307
+ export function describeGoCredential(resolved) {
308
+ const present = Boolean(resolved?.present);
309
+ return {
310
+ present,
311
+ source: resolved?.source ?? null,
312
+ ref: resolved?.ref ?? null,
313
+ fingerprint: resolved?.fingerprint ?? null,
314
+ masked: present ? '••••' : null,
315
+ dshCredentialsAvailable: Boolean(resolved?.dshCredentialsAvailable),
316
+ canSave: Boolean(resolved?.canSave),
317
+ canClear: Boolean(resolved?.canClear),
318
+ error: resolved?.error ?? null,
319
+ message: resolved?.message ? redactSecret(resolved.message) : null
320
+ };
321
+ }