@reopt-ai/workspace-sdk 0.0.0-stage → 0.1.0-rc.0

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,873 @@
1
+ import { J as platformResourceKeySchema, S as platformBrandUpsertInputSchema, U as platformPipelineUpsertInputSchema, j as platformErrorSchema, n as PlatformApiError, ot as SDK_VERSION, p as PLATFORM_OAUTH_CLIENT_PURPOSES, s as resolvePlatformUrls, w as platformBrandappUpsertInputSchema, y as PLATFORM_WEBHOOK_TRIGGERS } from "../client-BUatgjlv.js";
2
+ import { o as readClientKeyRing } from "../keys-6gwtNd0g.js";
3
+ import { r as createMachineClient } from "../client-XAvKlbbn.js";
4
+ import * as jose from "jose";
5
+ import { z } from "zod";
6
+
7
+ //#region src/installation/schema.ts
8
+ /**
9
+ * RFC-0034 §6.2 — 설치 매니페스트 스키마(zod). 서브 제품이 선언 파일에서 파생해 **자기 개인키로 서명**(JWS)하고,
10
+ * 리옵트가 본문의 `jwksUri`에서 키를 받아 검증한 뒤 운영자 승인을 기다린다. 승인되면 `workspace`는 RFC-0030 plan 엔진의
11
+ * 입력이 되고 `clients`·`resources`는 purpose 축 OAuthClient·OAuthResource 행이 된다.
12
+ */
13
+ const INSTALLATION_MANIFEST_SCHEMA_VERSION = 1;
14
+ /** JWS 재생 방어 — `exp ≤ iat + 600`. */
15
+ const INSTALLATION_MANIFEST_MAX_TTL_SECONDS = 600;
16
+ const INSTALLATION_STATUSES = [
17
+ "requested",
18
+ "approved",
19
+ "active",
20
+ "suspended",
21
+ "rejected",
22
+ "revoked"
23
+ ];
24
+ /**
25
+ * RFC-0043 — 설치의 종류. `brandapp`(기본, 생략과 같다)은 브랜드·브랜드앱을 만들고 클라이언트를 그 브랜드앱에 묶는다.
26
+ * `workspace`는 **브랜드앱을 만들지 않는** 워크스페이스 앱 — 회사 직원이 멤버로 들어오는 외부 어드민 같은 것.
27
+ * 클라이언트는 설치에만 묶이고 용도는 `connect`(멤버 위임 로그인)·`machine`(앱 서버) 둘뿐이다.
28
+ *
29
+ * 🔑 생략 가능(`optional`, 기본값 없음)인 이유: 기존 매니페스트의 해시(`manifestHash`)가 바뀌지 않아야 한다 —
30
+ * 기본값을 채우면 같은 매니페스트의 재요청이 "바뀐 매니페스트"로 읽힌다.
31
+ */
32
+ const INSTALLATION_KINDS = ["brandapp", "workspace"];
33
+ /** 워크스페이스 앱이 가질 수 있는 클라이언트 용도. */
34
+ const WORKSPACE_APP_CLIENT_PURPOSES = ["connect", "machine"];
35
+ /** 생략은 `brandapp`이다 — 읽는 쪽은 이 함수만 쓴다. */
36
+ function installationKindOf(manifest) {
37
+ return manifest.kind ?? "brandapp";
38
+ }
39
+ const httpsUrl = z.string().url().refine((value) => value.startsWith("https://"), { message: "must be an https:// URL" });
40
+ const installationSlugSchema = z.string().regex(/^[a-z][a-z0-9-]{1,62}$/, "slug must be [a-z][a-z0-9-]{1,62}");
41
+ const installationClientSchema = z.object({
42
+ purpose: z.enum(PLATFORM_OAUTH_CLIENT_PURPOSES),
43
+ scopes: z.array(z.string().min(1)).min(1),
44
+ redirectUris: z.array(z.string().url()).optional(),
45
+ postLogoutRedirectUris: z.array(z.string().url()).optional(),
46
+ requirePKCE: z.boolean().optional(),
47
+ name: z.string().min(1).max(80).optional()
48
+ }).strict().superRefine((value, ctx) => {
49
+ const human = value.purpose === "web" || value.purpose === "connect";
50
+ if (human && (!value.redirectUris || value.redirectUris.length === 0)) ctx.addIssue({
51
+ code: "custom",
52
+ path: ["redirectUris"],
53
+ message: `${value.purpose} clients need at least one redirectUri`
54
+ });
55
+ if (!human && value.redirectUris && value.redirectUris.length > 0) ctx.addIssue({
56
+ code: "custom",
57
+ path: ["redirectUris"],
58
+ message: `${value.purpose} clients do not use redirectUris`
59
+ });
60
+ });
61
+ const installationResourceSchema = z.object({
62
+ identifier: httpsUrl,
63
+ scopes: z.array(z.string().regex(/^svc:[a-z][a-z0-9-]*:[a-z0-9-]+:[a-z0-9-]+$/)).min(1),
64
+ accessTokenTtl: z.number().int().min(300).max(3600).optional()
65
+ }).strict();
66
+ const installationWebhookSchema = z.object({
67
+ url: httpsUrl,
68
+ triggers: z.array(z.enum(PLATFORM_WEBHOOK_TRIGGERS)).min(1),
69
+ secret: z.string().min(16).max(1024)
70
+ }).strict();
71
+ const installationWorkspaceSchema = z.object({
72
+ brands: z.record(platformResourceKeySchema, platformBrandUpsertInputSchema).optional(),
73
+ brandapps: z.record(platformResourceKeySchema, platformBrandappUpsertInputSchema).optional(),
74
+ works: z.object({ pipelines: z.record(platformResourceKeySchema, platformPipelineUpsertInputSchema).optional() }).strict().optional(),
75
+ webhooks: z.record(platformResourceKeySchema, installationWebhookSchema).optional()
76
+ }).strict();
77
+ const installationManifestSchema = z.object({
78
+ schemaVersion: z.literal(1),
79
+ kind: z.enum(INSTALLATION_KINDS).optional(),
80
+ slug: installationSlugSchema,
81
+ name: z.string().min(1).max(80),
82
+ workspaceId: z.string().uuid(),
83
+ jwksUri: httpsUrl,
84
+ backchannelUri: httpsUrl.optional(),
85
+ workspace: installationWorkspaceSchema,
86
+ clients: z.array(installationClientSchema).min(1),
87
+ resources: z.array(installationResourceSchema).optional(),
88
+ iat: z.number().int().nonnegative(),
89
+ exp: z.number().int().nonnegative()
90
+ }).strict().superRefine((value, ctx) => {
91
+ const purposes = /* @__PURE__ */ new Set();
92
+ const workspaceApp = installationKindOf(value) === "workspace";
93
+ const workspacePurposes = new Set(WORKSPACE_APP_CLIENT_PURPOSES);
94
+ value.clients.forEach((client, index) => {
95
+ if (purposes.has(client.purpose)) ctx.addIssue({
96
+ code: "custom",
97
+ path: [
98
+ "clients",
99
+ index,
100
+ "purpose"
101
+ ],
102
+ message: `one client per purpose — ${client.purpose} declared twice`
103
+ });
104
+ purposes.add(client.purpose);
105
+ if (workspaceApp && !workspacePurposes.has(client.purpose)) ctx.addIssue({
106
+ code: "custom",
107
+ path: [
108
+ "clients",
109
+ index,
110
+ "purpose"
111
+ ],
112
+ message: `workspace apps have no ${client.purpose} client — only ${WORKSPACE_APP_CLIENT_PURPOSES.join(" and ")}`
113
+ });
114
+ });
115
+ if (workspaceApp && Object.keys(value.workspace.brandapps ?? {}).length > 0) ctx.addIssue({
116
+ code: "custom",
117
+ path: ["workspace", "brandapps"],
118
+ message: "workspace apps do not declare brandapps"
119
+ });
120
+ if (value.exp <= value.iat) ctx.addIssue({
121
+ code: "custom",
122
+ path: ["exp"],
123
+ message: "exp must be after iat"
124
+ });
125
+ else if (value.exp - value.iat > 600) ctx.addIssue({
126
+ code: "custom",
127
+ path: ["exp"],
128
+ message: `exp must be within ${600}s of iat`
129
+ });
130
+ const identifiers = /* @__PURE__ */ new Set();
131
+ (value.resources ?? []).forEach((resource, index) => {
132
+ const origin = new URL(resource.identifier).origin;
133
+ if (identifiers.has(origin)) ctx.addIssue({
134
+ code: "custom",
135
+ path: [
136
+ "resources",
137
+ index,
138
+ "identifier"
139
+ ],
140
+ message: `resource origin ${origin} declared twice`
141
+ });
142
+ identifiers.add(origin);
143
+ resource.scopes.forEach((scope, scopeIndex) => {
144
+ if (!scope.startsWith(`svc:${value.slug}:`)) ctx.addIssue({
145
+ code: "custom",
146
+ path: [
147
+ "resources",
148
+ index,
149
+ "scopes",
150
+ scopeIndex
151
+ ],
152
+ message: `service scopes must be svc:${value.slug}:* for this installation`
153
+ });
154
+ });
155
+ });
156
+ });
157
+ function canonicalize(value) {
158
+ if (Array.isArray(value)) return value.map(canonicalize);
159
+ if (value && typeof value === "object") return Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonicalize(value[key])]));
160
+ return value;
161
+ }
162
+ /** 정규화 JSON — 해시·diff의 입력. `iat`·`exp`는 재생 방어용이라 빼고 센다. */
163
+ function canonicalManifestJson(manifest) {
164
+ const { iat: _iat, exp: _exp, ...body } = manifest;
165
+ return JSON.stringify(canonicalize(body));
166
+ }
167
+ async function manifestHash(manifest) {
168
+ const bytes = new TextEncoder().encode(canonicalManifestJson(manifest));
169
+ const digest = await crypto.subtle.digest("SHA-256", bytes);
170
+ return Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, "0")).join("");
171
+ }
172
+
173
+ //#endregion
174
+ //#region src/installation/jws.ts
175
+ /**
176
+ * RFC-0034 §6.1 — 매니페스트 JWS. 서브 제품이 자기 개인키(`readClientKeyRing().signing`)로 서명하고, 리옵트는
177
+ * **본문이 선언한 `jwksUri`**에서 키를 직접 받아 검증한다(헤더 `jku`는 무시 — TOFU의 근거는 사람의 승인이다).
178
+ * 재설치는 `active` 설치의 같은 jwksUri 키로만 서명된다(불변식 7).
179
+ */
180
+ const INSTALLATION_JWS_TYPE = "reopt-installation+jwt";
181
+ /** 매니페스트 본문에 `iat`·`exp`를 채우고 compact JWS로 서명한다. */
182
+ async function signManifest(body, options) {
183
+ const ttl = Math.min(600, Math.max(1, Math.floor(options.ttlSeconds ?? 300)));
184
+ const iat = Math.floor((options.now?.() ?? /* @__PURE__ */ new Date()).getTime() / 1e3);
185
+ const manifest = installationManifestSchema.parse({
186
+ ...body,
187
+ iat,
188
+ exp: iat + ttl
189
+ });
190
+ const key = await jose.importJWK(options.privateKeyJwk, options.privateKeyJwk.alg);
191
+ return {
192
+ jws: await new jose.SignJWT(manifest).setProtectedHeader({
193
+ alg: options.privateKeyJwk.alg,
194
+ kid: options.privateKeyJwk.kid,
195
+ typ: INSTALLATION_JWS_TYPE
196
+ }).sign(key),
197
+ manifest
198
+ };
199
+ }
200
+ const MANIFEST_VERIFY_ERROR_CODES = [
201
+ "INVALID_MANIFEST",
202
+ "SIGNATURE_INVALID",
203
+ "JWKS_UNREACHABLE",
204
+ "MANIFEST_EXPIRED",
205
+ "JWKS_HOST_NOT_ALLOWED"
206
+ ];
207
+ var ManifestVerifyError = class extends Error {
208
+ code;
209
+ issues;
210
+ constructor(code, message, issues) {
211
+ super(message);
212
+ this.name = "ManifestVerifyError";
213
+ this.code = code;
214
+ if (issues) this.issues = issues;
215
+ }
216
+ };
217
+ function decodeUnverified(jws) {
218
+ try {
219
+ return jose.decodeJwt(jws);
220
+ } catch {
221
+ throw new ManifestVerifyError("INVALID_MANIFEST", "Body is not a compact JWS");
222
+ }
223
+ }
224
+ function zodIssues(error) {
225
+ return error.issues?.map((issue) => ({
226
+ path: issue.path.map(String).join(".") || "(root)",
227
+ message: issue.message
228
+ }));
229
+ }
230
+ /**
231
+ * ① 본문을 (서명 전) 디코드해 스키마로 거른다 — `jwksUri`를 알아야 키를 가져온다.
232
+ * ② `jwksUri`에서 JWKS를 받아 서명·`typ`·`exp`를 검증한다.
233
+ * ③ 검증된 payload를 다시 파싱해 돌려준다(①의 값은 신뢰하지 않는다).
234
+ */
235
+ async function verifyManifestJws(jws, options = {}) {
236
+ const unverified = decodeUnverified(jws);
237
+ const first = installationManifestSchema.safeParse(unverified);
238
+ if (!first.success) throw new ManifestVerifyError("INVALID_MANIFEST", "Manifest does not match the schema", zodIssues(first.error));
239
+ const jwksUri = first.data.jwksUri;
240
+ if (options.expectedJwksUri && options.expectedJwksUri !== jwksUri) throw new ManifestVerifyError("SIGNATURE_INVALID", "Reinstall manifests must be signed by the installation's registered key");
241
+ if (options.allowJwksUri && !options.allowJwksUri(jwksUri)) throw new ManifestVerifyError("JWKS_HOST_NOT_ALLOWED", `jwksUri host is not allowed: ${jwksUri}`);
242
+ const fetchImpl = options.fetch ?? globalThis.fetch;
243
+ let jwks;
244
+ let jwksStatus = 0;
245
+ try {
246
+ const response = await fetchImpl(jwksUri, {
247
+ headers: { accept: "application/json" },
248
+ redirect: "error",
249
+ signal: AbortSignal.timeout(5e3)
250
+ });
251
+ jwksStatus = response.status;
252
+ if (!response.ok) throw new ManifestVerifyError("JWKS_UNREACHABLE", `JWKS responded ${response.status}`);
253
+ jwks = await response.json();
254
+ if (!Array.isArray(jwks.keys)) throw new Error("not a JWKS");
255
+ } catch (error) {
256
+ if (error instanceof ManifestVerifyError) throw error;
257
+ throw new ManifestVerifyError("JWKS_UNREACHABLE", `Could not fetch JWKS: ${error instanceof Error ? error.message : String(error)}`);
258
+ }
259
+ let payload;
260
+ let kid;
261
+ try {
262
+ const verified = await jose.jwtVerify(jws, jose.createLocalJWKSet(jwks), {
263
+ typ: INSTALLATION_JWS_TYPE,
264
+ clockTolerance: options.clockToleranceSeconds ?? 60,
265
+ currentDate: options.now?.()
266
+ });
267
+ payload = verified.payload;
268
+ kid = verified.protectedHeader.kid ?? "";
269
+ } catch (error) {
270
+ if (error.code === "ERR_JWT_EXPIRED") throw new ManifestVerifyError("MANIFEST_EXPIRED", "Manifest JWS expired");
271
+ throw new ManifestVerifyError("SIGNATURE_INVALID", `Manifest signature is not valid for ${jwksUri}`);
272
+ }
273
+ if (!kid) throw new ManifestVerifyError("SIGNATURE_INVALID", "Manifest JWS has no kid");
274
+ const second = installationManifestSchema.safeParse(payload);
275
+ if (!second.success) throw new ManifestVerifyError("INVALID_MANIFEST", "Manifest does not match the schema", zodIssues(second.error));
276
+ return {
277
+ manifest: second.data,
278
+ kid,
279
+ jwksStatus
280
+ };
281
+ }
282
+
283
+ //#endregion
284
+ //#region src/installation/assertion.ts
285
+ /**
286
+ * RFC-0034 §8 — 설치 단언(assertion). 아직 클라이언트가 없는 설치(`requested`)의 상태를 조회할 때, 매니페스트를
287
+ * 서명한 **같은 키**로 짧은 JWS를 만들어 `Authorization: Installation <jws>`로 보낸다. 리옵트는 설치 행의
288
+ * `jwksUri`에서 키를 받아 검증한다.
289
+ *
290
+ * 계약: header `{ alg, kid, typ: "reopt-installation-assertion+jwt" }`, payload `{ sub: installationId, iat, exp (≤ iat+300), jti }`.
291
+ */
292
+ const INSTALLATION_ASSERTION_TYPE = "reopt-installation-assertion+jwt";
293
+ const INSTALLATION_ASSERTION_MAX_TTL_SECONDS = 300;
294
+ const INSTALLATION_AUTH_SCHEME = "Installation";
295
+ async function signInstallationAssertion(options) {
296
+ if (!options.installationId) throw new Error("signInstallationAssertion: installationId is required");
297
+ const ttl = Math.min(300, Math.max(1, Math.floor(options.ttlSeconds ?? 60)));
298
+ const iat = Math.floor((options.now?.() ?? /* @__PURE__ */ new Date()).getTime() / 1e3);
299
+ const key = await jose.importJWK(options.privateKeyJwk, options.privateKeyJwk.alg);
300
+ return new jose.SignJWT({}).setProtectedHeader({
301
+ alg: options.privateKeyJwk.alg,
302
+ kid: options.privateKeyJwk.kid,
303
+ typ: INSTALLATION_ASSERTION_TYPE
304
+ }).setSubject(options.installationId).setIssuedAt(iat).setExpirationTime(iat + ttl).setJti(crypto.randomUUID()).sign(key);
305
+ }
306
+ /** `Authorization` 헤더 값. */
307
+ function installationAuthorizationHeader(jws) {
308
+ return `${INSTALLATION_AUTH_SCHEME} ${jws}`;
309
+ }
310
+
311
+ //#endregion
312
+ //#region src/installation/derive.ts
313
+ /**
314
+ * RFC-0034 §6.1 ② — RFC-0030 선언 파일(`reopt.workspace.ts`)에서 설치 매니페스트를 파생한다.
315
+ * `brands`·`brandapps`·`works`·`webhooks`는 그대로 `workspace`로 옮기고, `oauthClients`는 **무시**한다 —
316
+ * 설치의 클라이언트는 purpose 축 `clients[]`가 정본이다(한 설치에 용도당 하나).
317
+ */
318
+ var InstallationManifestError = class extends Error {
319
+ issues;
320
+ constructor(message, issues = []) {
321
+ super(message);
322
+ this.name = "InstallationManifestError";
323
+ this.issues = issues;
324
+ }
325
+ };
326
+ function deriveInstallationManifest(input) {
327
+ const { declaration } = input;
328
+ const webhooks = declaration.webhooks ? Object.fromEntries(Object.entries(declaration.webhooks).map(([key, hook]) => {
329
+ if (!hook.secret) throw new InstallationManifestError(`webhooks.${key}: a signing secret (16–1024 chars) is required — reopt signs every delivery (RFC-0034 phase 5)`, [{
330
+ path: `webhooks.${key}.secret`,
331
+ message: "required"
332
+ }]);
333
+ return [key, {
334
+ url: hook.url,
335
+ triggers: hook.triggers,
336
+ secret: hook.secret
337
+ }];
338
+ })) : void 0;
339
+ const candidate = {
340
+ schemaVersion: 1,
341
+ ...input.kind ? { kind: input.kind } : {},
342
+ slug: input.slug,
343
+ name: input.name,
344
+ workspaceId: input.workspaceId,
345
+ jwksUri: input.jwksUri,
346
+ ...input.backchannelUri ? { backchannelUri: input.backchannelUri } : {},
347
+ workspace: {
348
+ ...declaration.brands ? { brands: declaration.brands } : {},
349
+ ...declaration.brandapps ? { brandapps: declaration.brandapps } : {},
350
+ ...declaration.works ? { works: declaration.works } : {},
351
+ ...webhooks ? { webhooks } : {}
352
+ },
353
+ clients: input.clients,
354
+ ...input.resources ? { resources: input.resources } : {},
355
+ iat: 0,
356
+ exp: 1
357
+ };
358
+ const parsed = installationManifestSchema.safeParse(candidate);
359
+ if (!parsed.success) throw new InstallationManifestError("Derived manifest does not match the schema", parsed.error.issues.map((issue) => ({
360
+ path: issue.path.map(String).join(".") || "(root)",
361
+ message: issue.message
362
+ })));
363
+ const { iat: _iat, exp: _exp, ...body } = parsed.data;
364
+ return body;
365
+ }
366
+
367
+ //#endregion
368
+ //#region src/installation/client.ts
369
+ /**
370
+ * RFC-0034 §8 — `/v1/installations` 클라이언트(**서버 전용**, 개인키로 서명).
371
+ *
372
+ * 승인 전(`requested`)에는 클라이언트가 없으므로 매니페스트와 같은 키의 **단언**(`Authorization: Installation <jws>`)으로
373
+ * 조회하고, 활성화된 뒤에는 그 설치의 기계 클라이언트(`machine.clientId`, private_key_jwt + DPoP)로 나머지를 부른다.
374
+ */
375
+ function assertServerRuntime() {
376
+ if (typeof window !== "undefined" && typeof document !== "undefined") throw new Error("@reopt-ai/workspace-sdk/installation is server-only — it signs with the client private key.");
377
+ }
378
+ async function parseEnvelope(res) {
379
+ const text = await res.text();
380
+ let json = null;
381
+ if (text) try {
382
+ json = JSON.parse(text);
383
+ } catch {
384
+ json = null;
385
+ }
386
+ if (!res.ok) {
387
+ const parsed = platformErrorSchema.safeParse(json);
388
+ const error = parsed.success ? parsed.data.error : null;
389
+ throw new PlatformApiError({
390
+ status: res.status,
391
+ code: error?.code ?? "HTTP_ERROR",
392
+ message: error?.message ?? `Installation API responded ${res.status}`,
393
+ retryable: error?.retryable ?? (res.status >= 500 || res.status === 429),
394
+ ...error?.fields ? { fields: error.fields } : {},
395
+ ...res.headers.get("x-request-id") ? { requestId: res.headers.get("x-request-id") } : {}
396
+ });
397
+ }
398
+ const envelope = json;
399
+ if (!envelope || envelope.data === void 0) throw new PlatformApiError({
400
+ status: res.status,
401
+ code: "INVALID_RESPONSE",
402
+ message: "Installation API returned no data envelope",
403
+ retryable: false
404
+ });
405
+ return { data: envelope.data };
406
+ }
407
+ function createInstallationClient(config = {}) {
408
+ assertServerRuntime();
409
+ const urls = resolvePlatformUrls({
410
+ platformUrl: config.baseUrl,
411
+ idBaseUrl: config.idBaseUrl,
412
+ isProduction: config.isProduction
413
+ });
414
+ const resolvedRing = config.keyRing ?? (config.privateKeyJwk ? {
415
+ signing: config.privateKeyJwk,
416
+ published: [config.privateKeyJwk]
417
+ } : null) ?? readClientKeyRing();
418
+ if (!resolvedRing) throw new Error("createInstallationClient: a private key is required (keyRing, privateKeyJwk or REOPT_CLIENT_PRIVATE_KEY_JWK)");
419
+ const keyRing = resolvedRing;
420
+ const fetchImpl = config.fetch ?? globalThis.fetch;
421
+ const timeoutMs = config.timeoutMs ?? 1e4;
422
+ const nextRequestId = config.requestId ?? (() => crypto.randomUUID());
423
+ const base = `${urls.platformUrl}/v1/installations`;
424
+ let machine = null;
425
+ function requireMachine() {
426
+ if (!config.machine) throw new Error("createInstallationClient: this call needs the installation's machine client — pass machine: { clientId } once the installation is active");
427
+ machine ??= createMachineClient({
428
+ clientId: config.machine.clientId,
429
+ keyRing,
430
+ resource: urls.platformUrl,
431
+ scopes: config.machine.scopes ?? [],
432
+ idBaseUrl: urls.idBaseUrl,
433
+ fetch: fetchImpl,
434
+ timeoutMs
435
+ });
436
+ return machine;
437
+ }
438
+ async function send(method, url, init) {
439
+ const { data } = await parseEnvelope(await fetchImpl(url, {
440
+ method,
441
+ headers: {
442
+ ...init.auth,
443
+ accept: "application/json",
444
+ "x-request-id": nextRequestId(),
445
+ "x-sdk-version": SDK_VERSION,
446
+ ...init.contentType ? { "content-type": init.contentType } : {}
447
+ },
448
+ body: init.body,
449
+ signal: AbortSignal.timeout(timeoutMs)
450
+ }));
451
+ return data;
452
+ }
453
+ async function machineAuth(method, url) {
454
+ return requireMachine().headers({
455
+ method,
456
+ url
457
+ });
458
+ }
459
+ async function assertionAuth(id) {
460
+ return { authorization: installationAuthorizationHeader(await signInstallationAssertion({
461
+ installationId: id,
462
+ privateKeyJwk: keyRing.signing
463
+ })) };
464
+ }
465
+ return {
466
+ urls,
467
+ get kid() {
468
+ return keyRing.signing.kid;
469
+ },
470
+ async request(body, options = {}) {
471
+ const { jws } = await signManifest(body, {
472
+ privateKeyJwk: keyRing.signing,
473
+ ...options.ttlSeconds !== void 0 ? { ttlSeconds: options.ttlSeconds } : {}
474
+ });
475
+ const res = await fetchImpl(base, {
476
+ method: "POST",
477
+ headers: {
478
+ accept: "application/json",
479
+ "content-type": "application/jwt",
480
+ "x-request-id": nextRequestId(),
481
+ "x-sdk-version": SDK_VERSION
482
+ },
483
+ body: jws,
484
+ signal: AbortSignal.timeout(timeoutMs)
485
+ });
486
+ const { data } = await parseEnvelope(res);
487
+ return {
488
+ ...data,
489
+ created: res.status === 201
490
+ };
491
+ },
492
+ async get(id, options = {}) {
493
+ const mode = options.auth ?? (config.machine ? "machine" : "assertion");
494
+ const url = `${base}/${encodeURIComponent(id)}`;
495
+ return send("GET", url, { auth: mode === "machine" ? await machineAuth("GET", url) : await assertionAuth(id) });
496
+ },
497
+ async reinstall(id, body, options = {}) {
498
+ const url = `${base}/${encodeURIComponent(id)}/reinstall`;
499
+ const { jws } = await signManifest(body, {
500
+ privateKeyJwk: keyRing.signing,
501
+ ...options.ttlSeconds !== void 0 ? { ttlSeconds: options.ttlSeconds } : {}
502
+ });
503
+ return send("POST", url, {
504
+ auth: await machineAuth("POST", url),
505
+ body: jws,
506
+ contentType: "application/jwt"
507
+ });
508
+ },
509
+ async revoke(id) {
510
+ const url = `${base}/${encodeURIComponent(id)}`;
511
+ return send("DELETE", url, { auth: await machineAuth("DELETE", url) });
512
+ },
513
+ async refreshJwks(id) {
514
+ const url = `${base}/${encodeURIComponent(id)}/jwks-refresh`;
515
+ return send("POST", url, { auth: await machineAuth("POST", url) });
516
+ },
517
+ async health(id) {
518
+ const url = `${base}/${encodeURIComponent(id)}/health`;
519
+ return send("GET", url, { auth: await machineAuth("GET", url) });
520
+ }
521
+ };
522
+ }
523
+
524
+ //#endregion
525
+ //#region src/installation/backchannel.ts
526
+ /**
527
+ * RFC-0034 §7.7 — back-channel 통지 수신. 리옵트가 매니페스트의 `backchannelUri`로 `application/jwt` 본문(compact JWS)을
528
+ * POST한다. 서명은 리옵트 id의 JWKS(`${idBaseUrl}/api/auth/jwks`), 매체 타입 `"reopt-installation-event+jwt"`(header `typ` 또는 payload `typ` claim),
529
+ * payload `{ iss, aud: backchannelUri, iat, exp, jti, event, installation: { id, slug, status, workspaceId }, reason?, clients? }`.
530
+ *
531
+ * 통지는 **편의이지 정본이 아니다** — 카드는 `client.get(id)` 폴링으로도 같은 상태에 도달한다(§7.7).
532
+ */
533
+ const INSTALLATION_EVENT_TYPE = "reopt-installation-event+jwt";
534
+ const INSTALLATION_EVENT_NAMES = [
535
+ "installation.active",
536
+ "installation.rejected",
537
+ "installation.suspended",
538
+ "installation.resumed",
539
+ "installation.revoked"
540
+ ];
541
+ /**
542
+ * `now`는 핸들러와 **같은 시계**여야 한다 — 만료 판정(서명 검증)과 기억을 지우는 시점이 다른
543
+ * 시계를 보면, 핸들러가 아직 유효하다고 본 통지의 jti를 저장소가 먼저 잊어 재생이 통과한다.
544
+ */
545
+ function createMemoryBackchannelReplayStore(now = () => /* @__PURE__ */ new Date()) {
546
+ const seen = /* @__PURE__ */ new Map();
547
+ return { async reserve(jti, expiresAt) {
548
+ const current = now().getTime();
549
+ for (const [key, until] of seen) if (until <= current) seen.delete(key);
550
+ if (seen.has(jti)) return false;
551
+ seen.set(jti, expiresAt.getTime());
552
+ return true;
553
+ } };
554
+ }
555
+ function isEventName(value) {
556
+ return typeof value === "string" && INSTALLATION_EVENT_NAMES.includes(value);
557
+ }
558
+ function readEvent(payload) {
559
+ const installation = payload.installation;
560
+ if (!isEventName(payload.event) || !installation || typeof installation.id !== "string" || typeof installation.slug !== "string" || typeof installation.status !== "string" || typeof installation.workspaceId !== "string" || typeof payload.jti !== "string" || typeof payload.iat !== "number") return null;
561
+ const clients = Array.isArray(payload.clients) ? payload.clients.filter((c) => !!c && typeof c === "object" && typeof c.purpose === "string" && typeof c.clientId === "string") : void 0;
562
+ return {
563
+ event: payload.event,
564
+ installation: {
565
+ id: installation.id,
566
+ slug: installation.slug,
567
+ status: installation.status,
568
+ workspaceId: installation.workspaceId
569
+ },
570
+ ...typeof payload.reason === "string" ? { reason: payload.reason } : {},
571
+ ...clients ? { clients } : {},
572
+ iat: payload.iat,
573
+ jti: payload.jti
574
+ };
575
+ }
576
+ /**
577
+ * `(request: Request) => Response` — 204 처리됨 · 400 본문 없음/모양 틀림 · 401 서명·iss·aud·만료·재생 거절.
578
+ * `onEvent`가 던지면 500(리옵트가 재시도하지 않는다 — 폴링이 정본).
579
+ */
580
+ function createInstallationBackchannelHandler(options) {
581
+ const issuer = options.idBaseUrl.replace(/\/$/, "");
582
+ const jwks = options.jwks ?? jose.createRemoteJWKSet(new URL("/api/auth/jwks", issuer), {
583
+ cooldownDuration: 3e4,
584
+ cacheMaxAge: 6e5,
585
+ ...options.jwksFetch ? { [jose.customFetch]: options.jwksFetch } : {}
586
+ });
587
+ const clockToleranceSeconds = options.clockToleranceSeconds ?? 60;
588
+ const replayStore = options.replayStore ?? createMemoryBackchannelReplayStore(options.now);
589
+ return async (request) => {
590
+ const token = (await request.text()).trim();
591
+ if (!token || token.split(".").length !== 3) return new Response(null, { status: 400 });
592
+ let payload;
593
+ try {
594
+ const verified = await jose.jwtVerify(token, jwks, {
595
+ issuer,
596
+ audience: options.backchannelUri,
597
+ clockTolerance: clockToleranceSeconds,
598
+ currentDate: options.now?.()
599
+ });
600
+ payload = verified.payload;
601
+ if (verified.protectedHeader.typ !== "reopt-installation-event+jwt" && payload.typ !== "reopt-installation-event+jwt") return new Response(null, { status: 401 });
602
+ } catch {
603
+ return new Response(null, { status: 401 });
604
+ }
605
+ const event = readEvent(payload);
606
+ if (!event) return new Response(null, { status: 400 });
607
+ const expiresAt = /* @__PURE__ */ new Date(((typeof payload.exp === "number" ? payload.exp : event.iat + 300) + clockToleranceSeconds) * 1e3);
608
+ if (!await replayStore.reserve(event.jti, expiresAt)) return new Response(null, { status: 401 });
609
+ try {
610
+ await options.onEvent(event);
611
+ } catch {
612
+ return new Response(null, { status: 500 });
613
+ }
614
+ return new Response(null, { status: 204 });
615
+ };
616
+ }
617
+
618
+ //#endregion
619
+ //#region src/installation/connection.ts
620
+ function toConnectionStatus(status) {
621
+ switch (status) {
622
+ case "requested":
623
+ case "approved": return "pending";
624
+ case "active": return "connected";
625
+ case "suspended": return "suspended";
626
+ case "rejected": return "rejected";
627
+ case "revoked": return "revoked";
628
+ default: return "unconnected";
629
+ }
630
+ }
631
+ function primaryActionFor(status) {
632
+ switch (status) {
633
+ case "unconnected": return "request";
634
+ case "pending": return "cancel";
635
+ case "connected": return "rotate-key";
636
+ case "revoked":
637
+ case "rejected": return "reconnect";
638
+ default: return null;
639
+ }
640
+ }
641
+ /** §7.6 표의 문구 한 벌 — 앱마다 같은 말을 쓰게. */
642
+ function describeConnection(state) {
643
+ const r = state.record;
644
+ switch (state.status) {
645
+ case "unconnected": return {
646
+ title: "리옵트에 연결되지 않았습니다",
647
+ lines: ["선언 파일에서 파생한 매니페스트를 미리 보고, JWKS 자가 점검이 통과하면 연결을 요청합니다."],
648
+ primaryLabel: "리옵트에 연결 요청"
649
+ };
650
+ case "pending": return {
651
+ title: "운영자 승인을 기다립니다",
652
+ lines: [
653
+ `요청 시각 ${r?.requestedAt ?? "—"}`,
654
+ r?.consoleUrl ? `콘솔 상세: ${r.consoleUrl}` : "콘솔 상세 링크는 승인 요청 응답에 담깁니다.",
655
+ r?.status === "approved" ? "승인됐고 리옵트가 자원을 만들고 있습니다." : ""
656
+ ].filter(Boolean),
657
+ primaryLabel: "요청 취소"
658
+ };
659
+ case "connected": return {
660
+ title: "리옵트에 연결됨",
661
+ lines: [...(r?.clients ?? []).map((c) => `${c.purpose}: ${c.clientId}`), r?.health ? `건강 — 토큰 ${r.health.lastTokenAt ? "●" : "○"} · JWKS ${r.health.jwks.ok === null ? "—" : r.health.jwks.ok ? "●" : "✕"} · 웹훅 실패(7일) ${r.health.webhookFailures7d}` : "건강 정보는 새로 고침 뒤에 표시됩니다."],
662
+ primaryLabel: "키 회전"
663
+ };
664
+ case "suspended": return {
665
+ title: "리옵트 운영자가 일시정지했습니다",
666
+ lines: [r?.lastEvent?.reason ?? "사유는 콘솔 상세에 있습니다."],
667
+ primaryLabel: null
668
+ };
669
+ case "rejected": return {
670
+ title: "연결 요청이 거절됐습니다",
671
+ lines: [r?.decisionNote ?? r?.lastEvent?.reason ?? "사유 없음"],
672
+ primaryLabel: "다시 연결 요청"
673
+ };
674
+ case "revoked": return {
675
+ title: "연결이 해제됐습니다",
676
+ lines: [r?.lastEvent ? `${r.lastEvent.at} · ${r.lastEvent.event}` : "해제 시각은 콘솔 상세에 있습니다.", r?.lastEvent?.reason ?? ""].filter(Boolean),
677
+ primaryLabel: "다시 연결 요청"
678
+ };
679
+ }
680
+ }
681
+ function createReoptConnection(options) {
682
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
683
+ function toState(record) {
684
+ const status = toConnectionStatus(record?.status);
685
+ const machineClientId = record?.clients?.find((c) => c.purpose === "machine")?.clientId ?? null;
686
+ return {
687
+ status,
688
+ record,
689
+ primaryAction: primaryActionFor(status),
690
+ machineClientId
691
+ };
692
+ }
693
+ async function state() {
694
+ return toState(await options.store.load());
695
+ }
696
+ return {
697
+ state,
698
+ async describe() {
699
+ return describeConnection(await state());
700
+ },
701
+ async requestConnection(requestOptions = {}) {
702
+ const current = await options.store.load();
703
+ if (current && toConnectionStatus(current.status) === "pending") return current;
704
+ const result = await options.client.request(options.manifest, requestOptions);
705
+ const record = {
706
+ installationId: result.id,
707
+ status: result.status,
708
+ requestedAt: result.requestedAt,
709
+ ...result.consoleUrl ? { consoleUrl: result.consoleUrl } : {}
710
+ };
711
+ await options.store.save(record);
712
+ return record;
713
+ },
714
+ async refresh() {
715
+ const current = await options.store.load();
716
+ if (!current) return toState(null);
717
+ const view = await options.client.get(current.installationId, { auth: current.clients?.some((c) => c.purpose === "machine") ? "machine" : "assertion" });
718
+ const next = {
719
+ ...current,
720
+ status: view.status,
721
+ ...view.consoleUrl ? { consoleUrl: view.consoleUrl } : {},
722
+ ...view.decisionNote ? { decisionNote: view.decisionNote } : {},
723
+ clients: view.clients,
724
+ health: view.health,
725
+ refreshedAt: now().toISOString()
726
+ };
727
+ await options.store.save(next);
728
+ return toState(next);
729
+ },
730
+ async cancel() {
731
+ const current = await options.store.load();
732
+ if (!current || toConnectionStatus(current.status) !== "pending") throw new Error("cancel(): only a pending connection request can be cancelled locally");
733
+ await options.store.save(null);
734
+ },
735
+ async applyBackchannelEvent(event) {
736
+ const current = await options.store.load();
737
+ if (!current || current.installationId !== event.installation.id) return toState(current);
738
+ const next = {
739
+ ...current,
740
+ status: event.installation.status,
741
+ ...event.clients ? { clients: event.clients } : {},
742
+ ...event.reason && event.event === "installation.rejected" ? { decisionNote: event.reason } : {},
743
+ lastEvent: {
744
+ event: event.event,
745
+ at: (/* @__PURE__ */ new Date(event.iat * 1e3)).toISOString(),
746
+ ...event.reason ? { reason: event.reason } : {}
747
+ }
748
+ };
749
+ await options.store.save(next);
750
+ return toState(next);
751
+ },
752
+ async health() {
753
+ const current = await options.store.load();
754
+ if (!current || toConnectionStatus(current.status) !== "connected") return null;
755
+ const health = await options.client.health(current.installationId);
756
+ await options.store.save({
757
+ ...current,
758
+ health
759
+ });
760
+ return health;
761
+ }
762
+ };
763
+ }
764
+ /** 공개 JWKS URL이 200을 주고 현재 서명 키의 kid를 담고 있는가. */
765
+ async function selfCheckJwks(input) {
766
+ const fetchImpl = input.fetch ?? globalThis.fetch;
767
+ let res;
768
+ try {
769
+ res = await fetchImpl(input.publicUrl, {
770
+ headers: { accept: "application/json" },
771
+ signal: AbortSignal.timeout(5e3)
772
+ });
773
+ } catch {
774
+ return {
775
+ ok: false,
776
+ status: null,
777
+ reason: "unreachable",
778
+ kids: []
779
+ };
780
+ }
781
+ if (!res.ok) return {
782
+ ok: false,
783
+ status: res.status,
784
+ reason: "unreachable",
785
+ kids: []
786
+ };
787
+ let body = null;
788
+ try {
789
+ body = await res.json();
790
+ } catch {
791
+ body = null;
792
+ }
793
+ if (!body || !Array.isArray(body.keys)) return {
794
+ ok: false,
795
+ status: res.status,
796
+ reason: "not_json",
797
+ kids: []
798
+ };
799
+ const kids = body.keys.map((k) => k.kid).filter((k) => typeof k === "string");
800
+ if (!kids.includes(input.kid)) return {
801
+ ok: false,
802
+ status: res.status,
803
+ reason: "kid_missing",
804
+ kids
805
+ };
806
+ return {
807
+ ok: true,
808
+ status: res.status,
809
+ kids
810
+ };
811
+ }
812
+ /**
813
+ * 2단계 마법사의 현재 위치 — 키 링에 NEXT가 있으면 ①은 끝났다. ②는 `confirmKeyRecognized`가, ③은 env에서
814
+ * 옛 키를 지우고 NEXT를 현재로 올리는 사람의 일이다. 중간에 떠나도 안전하다(두 키 공존).
815
+ */
816
+ function planKeyRotation(input) {
817
+ return [
818
+ {
819
+ id: "publish-next",
820
+ done: input.keyRing.published.length > 1,
821
+ description: "새 키를 만들어 REOPT_CLIENT_PRIVATE_KEY_JWK_NEXT에 두고 배포한다 — JWKS에 두 키가 함께 실린다."
822
+ },
823
+ {
824
+ id: "confirm-recognized",
825
+ done: false,
826
+ description: "새 kid로 토큰 발급이 성공할 때까지 기다린다(리옵트 JWKS 캐시 최대 5분)."
827
+ },
828
+ {
829
+ id: "retire-old",
830
+ done: false,
831
+ description: "옛 키를 env에서 지우고 NEXT를 REOPT_CLIENT_PRIVATE_KEY_JWK로 올린다(옛 kid의 마지막 사용이 최근이면 경고)."
832
+ }
833
+ ];
834
+ }
835
+ /**
836
+ * 새 키로 토큰 발급을 반복 시도한다 — 리옵트의 클라이언트 JWKS 캐시(5분, kid 미스 재조회 없음) 때문에
837
+ * 최대 5분까지 걸린다. `machineClientFactory`는 **새 키로만** 서명하는 클라이언트를 만들어야 한다.
838
+ */
839
+ async function confirmKeyRecognized(input) {
840
+ const timeoutMs = Math.min(input.timeoutMs ?? 3e5, 3e5);
841
+ const intervalMs = Math.max(1e3, input.intervalMs ?? 15e3);
842
+ const sleep = input.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
843
+ const now = input.now ?? (() => Date.now());
844
+ const start = now();
845
+ const client = input.machineClientFactory(input.key);
846
+ let attempts = 0;
847
+ let lastError = "";
848
+ for (;;) {
849
+ attempts += 1;
850
+ try {
851
+ client.invalidateToken();
852
+ await client.getToken(true);
853
+ return {
854
+ recognized: true,
855
+ attempts,
856
+ elapsedMs: now() - start
857
+ };
858
+ } catch (error) {
859
+ lastError = error instanceof Error ? error.message : String(error);
860
+ }
861
+ if (now() - start + intervalMs > timeoutMs) return {
862
+ recognized: false,
863
+ attempts,
864
+ elapsedMs: now() - start,
865
+ lastError
866
+ };
867
+ await sleep(intervalMs);
868
+ }
869
+ }
870
+
871
+ //#endregion
872
+ export { INSTALLATION_ASSERTION_MAX_TTL_SECONDS, INSTALLATION_ASSERTION_TYPE, INSTALLATION_AUTH_SCHEME, INSTALLATION_EVENT_NAMES, INSTALLATION_EVENT_TYPE, INSTALLATION_JWS_TYPE, INSTALLATION_KINDS, INSTALLATION_MANIFEST_MAX_TTL_SECONDS, INSTALLATION_MANIFEST_SCHEMA_VERSION, INSTALLATION_STATUSES, InstallationManifestError, MANIFEST_VERIFY_ERROR_CODES, ManifestVerifyError, WORKSPACE_APP_CLIENT_PURPOSES, canonicalManifestJson, confirmKeyRecognized, createInstallationBackchannelHandler, createInstallationClient, createMemoryBackchannelReplayStore, createReoptConnection, deriveInstallationManifest, describeConnection, installationAuthorizationHeader, installationClientSchema, installationKindOf, installationManifestSchema, installationResourceSchema, installationSlugSchema, installationWebhookSchema, installationWorkspaceSchema, manifestHash, planKeyRotation, primaryActionFor, selfCheckJwks, signInstallationAssertion, signManifest, toConnectionStatus, verifyManifestJws };
873
+ //# sourceMappingURL=index.js.map