@c1m-public/platform-auth 0.12.0 → 0.14.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.
package/README.md CHANGED
@@ -11,7 +11,7 @@ need — the boundary is the subpath.
11
11
  ```
12
12
  . session: token reads, handoff, proxy gate, refresh (Web Request/Response)
13
13
  ./next session, server-only guard (Next route handlers)
14
- ./mcp-tokens self-service MCP PAT lifecycle (framework-neutral)
14
+ ./service-accounts operator-owned service accounts and credentials (framework-neutral)
15
15
  ./access authorization: snapshot, keys, predicates (framework-neutral)
16
16
  ./access/next access loader: require / forbidden / invalidate (Next, server-only)
17
17
  ./access/react <Can>, useCan, AccessProvider (client)
@@ -20,22 +20,28 @@ need — the boundary is the subpath.
20
20
  `next` and `react` are **optional** peer dependencies: a BFF that only reads
21
21
  sessions never needs them.
22
22
 
23
- ## `./mcp-tokens` — MCP personal access tokens
24
-
25
- `createMCPTokenClient` lists, mints, and revokes the signed-in platform user's
26
- own MCP tokens under `/api/v1/platform/auth/me/mcp-tokens`. The client resolves
27
- the bearer on every request, never retries mint or revoke, and emits bounded
28
- observations containing operation metadata but no URL, bearer, or PAT material.
29
-
30
- The subpath also exports `MCP_ACCESS_PERMISSION`,
31
- `MCP_TOKENS_MANAGE_PERMISSION`, `MCP_TOOL_PERMISSIONS`,
32
- `MCP_WILDCARD_TOOL_PERMISSIONS`, the request/response types, and the structural
33
- `MCPTokenAPIError` predicate. The permission ceiling `["*"]` follows future
34
- read-only tool permissions; mutating permissions must always be named
35
- explicitly. A minted `raw_token` is a one-time value: callers must keep it out
36
- of URLs, logs, storage, and telemetry. A `recent_authentication_required` API
37
- error is a step-up challenge, not an expired session; send the user through the
38
- host application's re-authentication path before retrying the mint.
23
+ ## `./service-accounts` — operator service accounts
24
+
25
+ `createServiceAccountClient` manages the operator-owned service accounts under
26
+ `/api/v1/platform/identity/service-accounts`: list, create, update, replace
27
+ grants, and list, mint or revoke credentials. Reads need
28
+ `SERVICE_ACCOUNTS_VIEW_PERMISSION`; every mutation needs
29
+ `SERVICE_ACCOUNTS_MANAGE_PERMISSION` and is never retried.
30
+
31
+ A credential is minted from **reviewed operation ids**, not from arbitrary
32
+ permissions: callers name `operation_ids` and the backend derives the
33
+ permission ceiling, so a caller cannot widen its own grant. The client also
34
+ holds the caller to the wire contract before a request leaves the process — a
35
+ `dash:<id>` audience must carry exactly its route Dash in `dash_ids`, a Dash
36
+ grant must name one Dash rather than `*`, `expires_in_days` is 1–30, and
37
+ `max_output_bytes` is 1–1048576.
38
+
39
+ Every mutation carries `expected_version`; a `409` with
40
+ `service_account_version_conflict` means the record moved under the caller and
41
+ the read has to be repeated. A `recent_authentication_required` API error is a
42
+ step-up challenge, not an expired session. The minted `secret` is one-time and
43
+ is checked to correlate with the credential it belongs to: keep it out of URLs,
44
+ logs, storage, and telemetry — the server never returns it again.
39
45
 
40
46
  ## `.` — session
41
47
 
@@ -1 +1 @@
1
- export { a as AccessEntry, b as AccessErrorCode, c as AccessScopeType, A as AccessSnapshot, d as AccessSnapshotError, D as DASH_PERMISSIONS, e as DASH_ROLES, f as DEFAULT_ACCESS_ENDPOINT_PATH, g as DashPermissionKey, h as DashRole, F as FetchAccessSnapshotOptions, L as LEADBROKER_PERMISSIONS, i as LeadBrokerPermissionKey, j as PIPELINE_STAGES, k as PLATFORM_PERMISSIONS, P as PermissionCheckOptions, l as PermissionKey, m as PipelineStage, n as PlatformPermissionKey, W as WORKSPACE_PERMISSIONS, o as WORKSPACE_ROLES, p as WorkspacePermissionKey, q as WorkspaceRole, r as appScopes, s as dashRole, t as emptySnapshot, u as entryCoversApp, v as fetchAccessSnapshot, w as hasAllPermissions, x as hasAnyPermission, y as hasPermission, z as hasWorkspacePermission, B as isAccessSnapshotError, C as isPipelineStage, E as isPlatformOwner, G as managedDashes, H as parseAccessSnapshot, I as permissionsFor } from '../index-D-cH_sfe.js';
1
+ export { a as AccessEntry, b as AccessErrorCode, c as AccessScopeType, A as AccessSnapshot, d as AccessSnapshotError, D as DASH_PERMISSIONS, e as DASH_ROLES, f as DEFAULT_ACCESS_ENDPOINT_PATH, g as DashPermissionKey, h as DashRole, F as FetchAccessSnapshotOptions, L as LEADBROKER_PERMISSIONS, i as LeadBrokerPermissionKey, j as PIPELINE_STAGES, k as PLATFORM_PERMISSIONS, P as PermissionCheckOptions, l as PermissionKey, m as PipelineStage, n as PlatformPermissionKey, W as WORKSPACE_PERMISSIONS, o as WORKSPACE_ROLES, p as WorkspacePermissionKey, q as WorkspaceRole, r as appScopes, s as dashRole, t as emptySnapshot, u as entryCoversApp, v as fetchAccessSnapshot, w as hasAllPermissions, x as hasAnyPermission, y as hasPermission, z as hasWorkspacePermission, B as isAccessSnapshotError, C as isPipelineStage, E as isPlatformOwner, G as managedDashes, H as parseAccessSnapshot, I as permissionsFor } from '../index-C-wuZVM9.js';
@@ -20,12 +20,13 @@ var PLATFORM_PERMISSIONS = [
20
20
  "platform.docs.manage",
21
21
  "platform.docs.view",
22
22
  "platform.mcp.access",
23
- "platform.mcp.tokens.manage",
24
23
  "platform.observability.manage",
25
24
  "platform.observability.view",
26
25
  "platform.offboarding.view",
27
26
  "platform.ops.manage",
28
27
  "platform.ops.view",
28
+ "platform.service_accounts.manage",
29
+ "platform.service_accounts.view",
29
30
  "platform.support.impersonate",
30
31
  "platform.support.sessions",
31
32
  "platform.tenants.archive",
@@ -47,6 +48,7 @@ var DASH_PERMISSIONS = [
47
48
  "dash.customers.manage",
48
49
  "dash.domains.manage",
49
50
  "dash.domains.view",
51
+ "dash.mcp.access",
50
52
  "dash.members.manage",
51
53
  "dash.ownership.transfer",
52
54
  "dash.plans.manage",
@@ -1,5 +1,5 @@
1
- import { A as AccessSnapshot, P as PermissionCheckOptions, R as Resolvable } from '../index-D-cH_sfe.js';
2
- export { a as AccessEntry, b as AccessErrorCode, c as AccessScopeType, d as AccessSnapshotError, D as DASH_PERMISSIONS, e as DASH_ROLES, f as DEFAULT_ACCESS_ENDPOINT_PATH, g as DashPermissionKey, h as DashRole, F as FetchAccessSnapshotOptions, L as LEADBROKER_PERMISSIONS, i as LeadBrokerPermissionKey, j as PIPELINE_STAGES, k as PLATFORM_PERMISSIONS, l as PermissionKey, m as PipelineStage, n as PlatformPermissionKey, W as WORKSPACE_PERMISSIONS, o as WORKSPACE_ROLES, p as WorkspacePermissionKey, q as WorkspaceRole, r as appScopes, s as dashRole, t as emptySnapshot, u as entryCoversApp, v as fetchAccessSnapshot, w as hasAllPermissions, x as hasAnyPermission, y as hasPermission, z as hasWorkspacePermission, B as isAccessSnapshotError, C as isPipelineStage, E as isPlatformOwner, G as managedDashes, H as parseAccessSnapshot, I as permissionsFor } from '../index-D-cH_sfe.js';
1
+ import { A as AccessSnapshot, P as PermissionCheckOptions, R as Resolvable } from '../index-C-wuZVM9.js';
2
+ export { a as AccessEntry, b as AccessErrorCode, c as AccessScopeType, d as AccessSnapshotError, D as DASH_PERMISSIONS, e as DASH_ROLES, f as DEFAULT_ACCESS_ENDPOINT_PATH, g as DashPermissionKey, h as DashRole, F as FetchAccessSnapshotOptions, L as LEADBROKER_PERMISSIONS, i as LeadBrokerPermissionKey, j as PIPELINE_STAGES, k as PLATFORM_PERMISSIONS, l as PermissionKey, m as PipelineStage, n as PlatformPermissionKey, W as WORKSPACE_PERMISSIONS, o as WORKSPACE_ROLES, p as WorkspacePermissionKey, q as WorkspaceRole, r as appScopes, s as dashRole, t as emptySnapshot, u as entryCoversApp, v as fetchAccessSnapshot, w as hasAllPermissions, x as hasAnyPermission, y as hasPermission, z as hasWorkspacePermission, B as isAccessSnapshotError, C as isPipelineStage, E as isPlatformOwner, G as managedDashes, H as parseAccessSnapshot, I as permissionsFor } from '../index-C-wuZVM9.js';
3
3
 
4
4
  /** Default cache tag for one subject's snapshot: `access:<subjectId>`. */
5
5
  declare function accessCacheTag(subjectId: string): string;
@@ -276,12 +276,13 @@ var PLATFORM_PERMISSIONS = [
276
276
  "platform.docs.manage",
277
277
  "platform.docs.view",
278
278
  "platform.mcp.access",
279
- "platform.mcp.tokens.manage",
280
279
  "platform.observability.manage",
281
280
  "platform.observability.view",
282
281
  "platform.offboarding.view",
283
282
  "platform.ops.manage",
284
283
  "platform.ops.view",
284
+ "platform.service_accounts.manage",
285
+ "platform.service_accounts.view",
285
286
  "platform.support.impersonate",
286
287
  "platform.support.sessions",
287
288
  "platform.tenants.archive",
@@ -303,6 +304,7 @@ var DASH_PERMISSIONS = [
303
304
  "dash.customers.manage",
304
305
  "dash.domains.manage",
305
306
  "dash.domains.view",
307
+ "dash.mcp.access",
306
308
  "dash.members.manage",
307
309
  "dash.ownership.transfer",
308
310
  "dash.plans.manage",
@@ -1,8 +1,8 @@
1
1
  /** Platform-operator permission keys. */
2
- declare const PLATFORM_PERMISSIONS: readonly ["affiliates.enrollments.manage", "affiliates.finance.manage", "affiliates.partners.manage", "affiliates.programmes.manage", "affiliates.view", "linkservice.domains.manage", "linkservice.links.manage", "linkservice.qr.manage", "linkservice.view", "platform.admin.view", "platform.audit.view", "platform.auth.manage", "platform.billing.manage", "platform.billing.view", "platform.channels.manage", "platform.channels.view", "platform.config.manage", "platform.docs.manage", "platform.docs.view", "platform.mcp.access", "platform.mcp.tokens.manage", "platform.observability.manage", "platform.observability.view", "platform.offboarding.view", "platform.ops.manage", "platform.ops.view", "platform.support.impersonate", "platform.support.sessions", "platform.tenants.archive", "platform.tenants.manage", "platform.tenants.restore", "platform.tenants.view", "platform.users.deactivate", "platform.users.delete", "platform.users.invite", "platform.users.manage_access", "platform.users.reactivate", "platform.users.view"];
2
+ declare const PLATFORM_PERMISSIONS: readonly ["affiliates.enrollments.manage", "affiliates.finance.manage", "affiliates.partners.manage", "affiliates.programmes.manage", "affiliates.view", "linkservice.domains.manage", "linkservice.links.manage", "linkservice.qr.manage", "linkservice.view", "platform.admin.view", "platform.audit.view", "platform.auth.manage", "platform.billing.manage", "platform.billing.view", "platform.channels.manage", "platform.channels.view", "platform.config.manage", "platform.docs.manage", "platform.docs.view", "platform.mcp.access", "platform.observability.manage", "platform.observability.view", "platform.offboarding.view", "platform.ops.manage", "platform.ops.view", "platform.service_accounts.manage", "platform.service_accounts.view", "platform.support.impersonate", "platform.support.sessions", "platform.tenants.archive", "platform.tenants.manage", "platform.tenants.restore", "platform.tenants.view", "platform.users.deactivate", "platform.users.delete", "platform.users.invite", "platform.users.manage_access", "platform.users.reactivate", "platform.users.view"];
3
3
  type PlatformPermissionKey = (typeof PLATFORM_PERMISSIONS)[number];
4
4
  /** Dash-owner permission keys (granted at dash scope, mirrored from the membership role). */
5
- declare const DASH_PERMISSIONS: readonly ["dash.apps.manage", "dash.billing.manage", "dash.billing.view", "dash.channels.manage", "dash.customers.manage", "dash.domains.manage", "dash.domains.view", "dash.members.manage", "dash.ownership.transfer", "dash.plans.manage", "dash.plans.view", "dash.publish", "dash.settings.manage", "dash.workspaces.admin", "dash.workspaces.manage", "dash.workspaces.view"];
5
+ declare const DASH_PERMISSIONS: readonly ["dash.apps.manage", "dash.billing.manage", "dash.billing.view", "dash.channels.manage", "dash.customers.manage", "dash.domains.manage", "dash.domains.view", "dash.mcp.access", "dash.members.manage", "dash.ownership.transfer", "dash.plans.manage", "dash.plans.view", "dash.publish", "dash.settings.manage", "dash.workspaces.admin", "dash.workspaces.manage", "dash.workspaces.view"];
6
6
  type DashPermissionKey = (typeof DASH_PERMISSIONS)[number];
7
7
  /** Membership-mirrored dash role bundles (grant keys at dash scope). */
8
8
  declare const DASH_ROLES: readonly ["dash.admin", "dash.owner"];
@@ -0,0 +1,149 @@
1
+ declare const SERVICE_ACCOUNTS_VIEW_PERMISSION: "platform.service_accounts.view";
2
+ declare const SERVICE_ACCOUNTS_MANAGE_PERMISSION: "platform.service_accounts.manage";
3
+ type ServiceAccountAudience = "platform" | `dash:${string}`;
4
+ type ServiceAccountGrantScope = "platform" | "dash_id";
5
+ type ServiceAccountOperation = "platform.identity.service_accounts.list" | "platform.identity.service_accounts.create" | "platform.identity.service_accounts.get" | "platform.identity.service_accounts.update" | "platform.identity.service_accounts.grants.list" | "platform.identity.service_accounts.grants.replace" | "platform.identity.service_accounts.credentials.list" | "platform.identity.service_accounts.credentials.mint" | "platform.identity.service_accounts.credentials.revoke";
6
+ type ServiceAccountRequestOutcome = "success" | "api_error" | "network_error" | "timeout" | "invalid_response" | "cancelled";
7
+ interface ServiceAccountView {
8
+ id: string;
9
+ name: string;
10
+ purpose: string;
11
+ owner_user_id: string;
12
+ enabled: boolean;
13
+ version: number;
14
+ created_by: string;
15
+ updated_by: string;
16
+ created_at: string;
17
+ updated_at: string;
18
+ }
19
+ interface ServiceAccountEnvelope {
20
+ service_account: ServiceAccountView;
21
+ }
22
+ interface ServiceAccountPage {
23
+ items: ServiceAccountView[];
24
+ next_cursor?: string;
25
+ has_more: boolean;
26
+ }
27
+ interface ServiceAccountGrant {
28
+ grant_key: string;
29
+ scope_type: string;
30
+ scope_id: string;
31
+ id?: string;
32
+ subject_id?: string;
33
+ subject_type?: string;
34
+ granted_by?: string;
35
+ created_at?: string;
36
+ }
37
+ interface ServiceAccountGrantInput {
38
+ grant_key: string;
39
+ scope_type: ServiceAccountGrantScope;
40
+ scope_id: string;
41
+ }
42
+ interface ServiceAccountGrantPage {
43
+ items: ServiceAccountGrant[];
44
+ }
45
+ interface ServiceAccountCredential {
46
+ id: string;
47
+ service_account_id: string;
48
+ name: string;
49
+ audience: ServiceAccountAudience;
50
+ permissions: string[];
51
+ operation_ids: string[];
52
+ dash_ids: string[];
53
+ max_output_bytes: number;
54
+ created_by: string;
55
+ created_at: string;
56
+ expires_at: string;
57
+ last_used_at?: string;
58
+ revoked_at?: string;
59
+ }
60
+ interface ServiceAccountCredentialPage {
61
+ items: ServiceAccountCredential[];
62
+ next_cursor?: string;
63
+ has_more: boolean;
64
+ }
65
+ interface CreateServiceAccountInput {
66
+ name: string;
67
+ purpose: string;
68
+ owner_user_id: string;
69
+ reason: string;
70
+ }
71
+ interface UpdateServiceAccountInput extends CreateServiceAccountInput {
72
+ enabled: boolean;
73
+ expected_version: number;
74
+ }
75
+ interface ReplaceServiceAccountGrantsInput {
76
+ grants: ServiceAccountGrantInput[];
77
+ expected_version: number;
78
+ reason: string;
79
+ }
80
+ type ServiceAccountCredentialTemplate = "read_only" | "full" | "custom";
81
+ interface MintServiceAccountCredentialInput {
82
+ name: string;
83
+ audience: ServiceAccountAudience;
84
+ /** Authority template; `custom` names the permissions to carry. Operations are derived server-side. */
85
+ template: ServiceAccountCredentialTemplate;
86
+ permissions?: string[];
87
+ dash_ids: string[];
88
+ expires_in_days: number;
89
+ expected_version: number;
90
+ reason: string;
91
+ max_output_bytes?: number;
92
+ }
93
+ interface MintServiceAccountCredentialResponse {
94
+ credential: ServiceAccountCredential;
95
+ /** One-time presented secret. The server never returns it again. */
96
+ secret: string;
97
+ }
98
+ interface RevokeServiceAccountCredentialInput {
99
+ expected_version: number;
100
+ reason: string;
101
+ }
102
+ interface ServiceAccountListParams {
103
+ cursor?: string;
104
+ limit?: number;
105
+ }
106
+ interface ServiceAccountRequestObservation {
107
+ operation: ServiceAccountOperation;
108
+ method: string;
109
+ outcome: ServiceAccountRequestOutcome;
110
+ status: number;
111
+ requestId: string;
112
+ durationMs: number;
113
+ attempts: number;
114
+ }
115
+ interface CreateServiceAccountClientOptions {
116
+ baseUrl: string;
117
+ getAccessToken: () => Promise<string | null | undefined> | string | null | undefined;
118
+ getHeaders?: () => Promise<HeadersInit | undefined> | HeadersInit | undefined;
119
+ fetch?: typeof globalThis.fetch;
120
+ /** Per attempt (default 10000). */
121
+ timeoutMs?: number;
122
+ /** Additional attempts for GET only (default 1). Mutations are never retried. */
123
+ retryAttempts?: number;
124
+ /** Cap on one retry delay (default 2000). */
125
+ maxRetryDelayMs?: number;
126
+ observe?: (event: ServiceAccountRequestObservation) => void;
127
+ signal?: AbortSignal;
128
+ }
129
+ declare class ServiceAccountAPIError extends Error {
130
+ readonly status: number;
131
+ readonly code: string;
132
+ readonly requestId: string;
133
+ constructor(message: string, status: number, code: string, requestId: string);
134
+ }
135
+ declare function isServiceAccountAPIError(error: unknown): error is ServiceAccountAPIError;
136
+ declare function createServiceAccountClient(options: CreateServiceAccountClientOptions): {
137
+ readonly list: (params?: ServiceAccountListParams) => Promise<ServiceAccountPage>;
138
+ readonly get: (serviceAccountID: string) => Promise<ServiceAccountEnvelope>;
139
+ readonly create: (input: CreateServiceAccountInput) => Promise<ServiceAccountEnvelope>;
140
+ readonly update: (serviceAccountID: string, input: UpdateServiceAccountInput) => Promise<ServiceAccountEnvelope>;
141
+ readonly listGrants: (serviceAccountID: string) => Promise<ServiceAccountGrantPage>;
142
+ readonly replaceGrants: (serviceAccountID: string, input: ReplaceServiceAccountGrantsInput) => Promise<ServiceAccountEnvelope>;
143
+ readonly listCredentials: (serviceAccountID: string, params?: ServiceAccountListParams) => Promise<ServiceAccountCredentialPage>;
144
+ readonly mintCredential: (serviceAccountID: string, input: MintServiceAccountCredentialInput) => Promise<MintServiceAccountCredentialResponse>;
145
+ readonly revokeCredential: (serviceAccountID: string, credentialID: string, input: RevokeServiceAccountCredentialInput) => Promise<ServiceAccountEnvelope>;
146
+ };
147
+ type ServiceAccountClient = ReturnType<typeof createServiceAccountClient>;
148
+
149
+ export { type CreateServiceAccountClientOptions, type CreateServiceAccountInput, type MintServiceAccountCredentialInput, type MintServiceAccountCredentialResponse, type ReplaceServiceAccountGrantsInput, type RevokeServiceAccountCredentialInput, SERVICE_ACCOUNTS_MANAGE_PERMISSION, SERVICE_ACCOUNTS_VIEW_PERMISSION, ServiceAccountAPIError, type ServiceAccountAudience, type ServiceAccountClient, type ServiceAccountCredential, type ServiceAccountCredentialPage, type ServiceAccountCredentialTemplate, type ServiceAccountEnvelope, type ServiceAccountGrant, type ServiceAccountGrantInput, type ServiceAccountGrantPage, type ServiceAccountGrantScope, type ServiceAccountListParams, type ServiceAccountOperation, type ServiceAccountPage, type ServiceAccountRequestObservation, type ServiceAccountRequestOutcome, type ServiceAccountView, type UpdateServiceAccountInput, createServiceAccountClient, isServiceAccountAPIError };
@@ -0,0 +1,484 @@
1
+ // ../transport/src/index.ts
2
+ var RETRYABLE_STATUSES = /* @__PURE__ */ new Set([429, 502, 503, 504]);
3
+ var TransportError = class extends Error {
4
+ constructor(failure) {
5
+ super(failure.message || failure.outcome);
6
+ this.failure = failure;
7
+ this.name = "TransportError";
8
+ }
9
+ failure;
10
+ };
11
+ function isTransportError(error) {
12
+ return error instanceof TransportError || typeof error === "object" && error !== null && error.name === "TransportError";
13
+ }
14
+ function positiveNumber(value, label, fail) {
15
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) throw fail(`${label} must be a positive finite number`);
16
+ return value;
17
+ }
18
+ function nonNegativeInteger(value, label, fail) {
19
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw fail(`${label} must be a non-negative safe integer`);
20
+ return value;
21
+ }
22
+ function requiredString(value, label, fail) {
23
+ const normalized = typeof value === "string" ? value.trim() : "";
24
+ if (!normalized) throw fail(`${label} is required`);
25
+ return normalized;
26
+ }
27
+ function backoffDelay(attempt, maxDelayMs) {
28
+ const base = Math.min(250 * 2 ** Math.max(attempt, 0), maxDelayMs);
29
+ return Math.floor(Math.random() * base);
30
+ }
31
+ function retryDelay(response, attempt, maxDelayMs) {
32
+ const value = response.headers.get("Retry-After");
33
+ if (!value) return backoffDelay(attempt, maxDelayMs);
34
+ const seconds = Number(value);
35
+ if (Number.isFinite(seconds)) return Math.min(Math.max(seconds * 1e3, 0), maxDelayMs);
36
+ const date = Date.parse(value);
37
+ return Number.isNaN(date) ? backoffDelay(attempt, maxDelayMs) : Math.min(Math.max(date - Date.now(), 0), maxDelayMs);
38
+ }
39
+ function wait(ms) {
40
+ return ms <= 0 ? Promise.resolve() : new Promise((resolve) => setTimeout(resolve, ms));
41
+ }
42
+ function combineSignals(...signals) {
43
+ const active = signals.filter((signal) => Boolean(signal));
44
+ if (active.length === 0) return void 0;
45
+ if (active.length === 1) return active[0];
46
+ return AbortSignal.any(active);
47
+ }
48
+ function isRetryableRequest(method, headers, retry) {
49
+ if (method === "GET") return true;
50
+ return retry.idempotentWrites === true && headers.has("Idempotency-Key");
51
+ }
52
+ async function performRequest(transport, url, init, observe, decode) {
53
+ const method = (init.method ?? "GET").toUpperCase();
54
+ const headers = new Headers(init.headers);
55
+ const startedAt = Date.now();
56
+ const retryable = isRetryableRequest(method, headers, transport.retry);
57
+ const maxAttempts = retryable ? transport.retry.attempts : 0;
58
+ let attempts = 0;
59
+ let status = 0;
60
+ let requestId = "";
61
+ let outcome = "network_error";
62
+ const fail = (failure) => {
63
+ outcome = failure.outcome;
64
+ throw new TransportError({ requestId, ...failure });
65
+ };
66
+ try {
67
+ let response;
68
+ for (let attempt = 0; attempt <= maxAttempts; attempt += 1) {
69
+ attempts = attempt + 1;
70
+ const controller = new AbortController();
71
+ const timeout = setTimeout(() => controller.abort(), transport.timeoutMs);
72
+ try {
73
+ response = await transport.fetch(url, {
74
+ ...init,
75
+ method,
76
+ headers,
77
+ signal: combineSignals(transport.signal, init.signal, controller.signal)
78
+ });
79
+ } catch {
80
+ if (controller.signal.aborted) fail({ outcome: "timeout", status: 0, code: "", message: "" });
81
+ if (transport.signal?.aborted || init.signal?.aborted) fail({ outcome: "cancelled", status: 0, code: "", message: "" });
82
+ if (attempt < maxAttempts) {
83
+ await wait(backoffDelay(attempt, transport.retry.maxDelayMs));
84
+ continue;
85
+ }
86
+ fail({ outcome: "network_error", status: 0, code: "", message: "" });
87
+ } finally {
88
+ clearTimeout(timeout);
89
+ }
90
+ if (!RETRYABLE_STATUSES.has(response.status) || attempt === maxAttempts) break;
91
+ await wait(retryDelay(response, attempt, transport.retry.maxDelayMs));
92
+ }
93
+ if (!response) return fail({ outcome: "network_error", status: 0, code: "", message: "" });
94
+ status = response.status;
95
+ requestId = response.headers.get("X-Request-ID") ?? "";
96
+ if (!response.ok) {
97
+ const envelope = await response.json().catch(() => ({}));
98
+ if (typeof envelope.request_id === "string") requestId = envelope.request_id;
99
+ return fail({
100
+ outcome: "api_error",
101
+ status,
102
+ code: typeof envelope.code === "string" ? envelope.code : "",
103
+ message: typeof envelope.message === "string" ? envelope.message : "",
104
+ requestId
105
+ });
106
+ }
107
+ let payload;
108
+ try {
109
+ if (status === 204) {
110
+ payload = void 0;
111
+ } else {
112
+ const text = await response.text();
113
+ const parsed = text ? JSON.parse(text) : void 0;
114
+ payload = decode ? decode(parsed) : parsed;
115
+ }
116
+ } catch {
117
+ return fail({ outcome: "invalid_response", status, code: "", message: "", requestId });
118
+ }
119
+ outcome = "success";
120
+ return { payload, status, requestId };
121
+ } finally {
122
+ if (observe) {
123
+ try {
124
+ observe({ method, outcome, status, requestId, durationMs: Math.max(0, Date.now() - startedAt), attempts });
125
+ } catch {
126
+ }
127
+ }
128
+ }
129
+ }
130
+
131
+ // src/service-accounts.ts
132
+ var SERVICE_ACCOUNTS_VIEW_PERMISSION = "platform.service_accounts.view";
133
+ var SERVICE_ACCOUNTS_MANAGE_PERMISSION = "platform.service_accounts.manage";
134
+ var ServiceAccountAPIError = class extends Error {
135
+ constructor(message, status, code, requestId) {
136
+ super(message);
137
+ this.status = status;
138
+ this.code = code;
139
+ this.requestId = requestId;
140
+ this.name = "ServiceAccountAPIError";
141
+ }
142
+ status;
143
+ code;
144
+ requestId;
145
+ };
146
+ function isServiceAccountAPIError(error) {
147
+ return error instanceof ServiceAccountAPIError || typeof error === "object" && error !== null && error.name === "ServiceAccountAPIError" && typeof error.status === "number" && typeof error.code === "string" && typeof error.requestId === "string";
148
+ }
149
+ var basePath = "/api/v1/platform/identity/service-accounts";
150
+ var uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
151
+ var credentialIDPattern = /^[0-9a-f]{32}$/;
152
+ var timestampPattern = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;
153
+ var secretPattern = /^mml_sa_([0-9a-f]{32})_([0-9a-f]{64})$/;
154
+ var configurationError = (message) => new Error(message);
155
+ function invalidResponse() {
156
+ throw new Error("invalid Service Account response");
157
+ }
158
+ function objectValue(value) {
159
+ if (typeof value !== "object" || value === null || Array.isArray(value)) invalidResponse();
160
+ return value;
161
+ }
162
+ function responseString(value, options = {}) {
163
+ if (value === void 0 && options.optional) return void 0;
164
+ if (typeof value !== "string" || value.length === 0) invalidResponse();
165
+ if (options.pattern && !options.pattern.test(value)) invalidResponse();
166
+ if (options.timestamp && (!timestampPattern.test(value) || !Number.isFinite(Date.parse(value)))) invalidResponse();
167
+ return value;
168
+ }
169
+ function responseStrings(value) {
170
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string" || entry.length === 0)) {
171
+ invalidResponse();
172
+ }
173
+ return [...value];
174
+ }
175
+ function positiveIntegerResponse(value) {
176
+ if (!Number.isSafeInteger(value) || Number(value) < 1) invalidResponse();
177
+ return Number(value);
178
+ }
179
+ function parseServiceAccount(value) {
180
+ const account = objectValue(value);
181
+ if (typeof account.enabled !== "boolean") invalidResponse();
182
+ return {
183
+ id: responseString(account.id, { pattern: uuidPattern }),
184
+ name: responseString(account.name),
185
+ purpose: responseString(account.purpose),
186
+ owner_user_id: responseString(account.owner_user_id),
187
+ enabled: account.enabled,
188
+ version: positiveIntegerResponse(account.version),
189
+ created_by: responseString(account.created_by),
190
+ updated_by: responseString(account.updated_by),
191
+ created_at: responseString(account.created_at, { timestamp: true }),
192
+ updated_at: responseString(account.updated_at, { timestamp: true })
193
+ };
194
+ }
195
+ function parseServiceAccountEnvelope(value) {
196
+ return { service_account: parseServiceAccount(objectValue(value).service_account) };
197
+ }
198
+ function parsePage(value, parseItem) {
199
+ const page = objectValue(value);
200
+ if (!Array.isArray(page.items) || typeof page.has_more !== "boolean") invalidResponse();
201
+ const nextCursor = responseString(page.next_cursor, { optional: true });
202
+ if (Boolean(nextCursor) !== page.has_more) invalidResponse();
203
+ return { items: page.items.map(parseItem), next_cursor: nextCursor, has_more: page.has_more };
204
+ }
205
+ function parseGrant(value) {
206
+ const grant = objectValue(value);
207
+ return {
208
+ grant_key: responseString(grant.grant_key),
209
+ scope_type: responseString(grant.scope_type),
210
+ scope_id: responseString(grant.scope_id),
211
+ id: responseString(grant.id, { optional: true }),
212
+ subject_id: responseString(grant.subject_id, { optional: true }),
213
+ subject_type: responseString(grant.subject_type, { optional: true }),
214
+ granted_by: responseString(grant.granted_by, { optional: true }),
215
+ created_at: responseString(grant.created_at, { optional: true, timestamp: true })
216
+ };
217
+ }
218
+ function parseCredential(value) {
219
+ const credential = objectValue(value);
220
+ const audience = responseString(credential.audience);
221
+ if (audience !== "platform" && !audience.startsWith("dash:")) invalidResponse();
222
+ return {
223
+ id: responseString(credential.id, { pattern: credentialIDPattern }),
224
+ service_account_id: responseString(credential.service_account_id, { pattern: uuidPattern }),
225
+ name: responseString(credential.name),
226
+ audience,
227
+ permissions: responseStrings(credential.permissions),
228
+ operation_ids: responseStrings(credential.operation_ids),
229
+ dash_ids: responseStrings(credential.dash_ids),
230
+ max_output_bytes: positiveIntegerResponse(credential.max_output_bytes),
231
+ created_by: responseString(credential.created_by),
232
+ created_at: responseString(credential.created_at, { timestamp: true }),
233
+ expires_at: responseString(credential.expires_at, { timestamp: true }),
234
+ last_used_at: responseString(credential.last_used_at, { optional: true, timestamp: true }),
235
+ revoked_at: responseString(credential.revoked_at, { optional: true, timestamp: true })
236
+ };
237
+ }
238
+ function parseMintedCredential(value) {
239
+ const minted = objectValue(value);
240
+ const credential = parseCredential(minted.credential);
241
+ const secret = responseString(minted.secret);
242
+ const match = secret.match(secretPattern);
243
+ if (!match || match[1] !== credential.id) invalidResponse();
244
+ return { credential, secret };
245
+ }
246
+ function canonicalID(value, label, pattern) {
247
+ const id = requiredString(value, label, configurationError);
248
+ if (!pattern.test(id)) throw configurationError(`${label} is invalid`);
249
+ return id;
250
+ }
251
+ function version(value) {
252
+ if (!Number.isSafeInteger(value) || value < 1) throw configurationError("expected_version must be a positive integer");
253
+ return value;
254
+ }
255
+ function reason(value) {
256
+ const normalized = requiredString(value, "reason", configurationError);
257
+ if (normalized.length > 500) throw configurationError("reason must be 500 characters or fewer");
258
+ return normalized;
259
+ }
260
+ function accountFields(input) {
261
+ const name = requiredString(input.name, "name", configurationError);
262
+ const purpose = requiredString(input.purpose, "purpose", configurationError);
263
+ const ownerUserID = requiredString(input.owner_user_id, "owner_user_id", configurationError);
264
+ if (name.length > 64) throw configurationError("name must be 64 characters or fewer");
265
+ if (purpose.length > 500) throw configurationError("purpose must be 500 characters or fewer");
266
+ return { name, purpose, owner_user_id: ownerUserID, reason: reason(input.reason) };
267
+ }
268
+ function listQuery(params) {
269
+ const query = new URLSearchParams();
270
+ const cursor = params.cursor?.trim();
271
+ if (cursor) query.set("cursor", cursor);
272
+ if (params.limit !== void 0) {
273
+ const limit = positiveNumber(params.limit, "limit", configurationError);
274
+ if (!Number.isSafeInteger(limit) || limit > 100) throw configurationError("limit must be an integer from 1 to 100");
275
+ query.set("limit", String(limit));
276
+ }
277
+ return query.size ? `?${query}` : "";
278
+ }
279
+ function grantInput(value) {
280
+ const grantKey = requiredString(value.grant_key, "grant_key", configurationError);
281
+ if (value.scope_type !== "platform" && value.scope_type !== "dash_id") {
282
+ throw configurationError("scope_type must be platform or dash_id");
283
+ }
284
+ const scopeID = requiredString(value.scope_id, "scope_id", configurationError);
285
+ if (value.scope_type === "platform" && scopeID !== "*") {
286
+ throw configurationError('platform grants must use scope_id "*"');
287
+ }
288
+ if (value.scope_type === "dash_id" && scopeID === "*") {
289
+ throw configurationError("service-account Dash grants must name one Dash");
290
+ }
291
+ return { grant_key: grantKey, scope_type: value.scope_type, scope_id: scopeID };
292
+ }
293
+ function mintInput(value) {
294
+ const name = requiredString(value.name, "name", configurationError);
295
+ if (name.length > 64) throw configurationError("name must be 64 characters or fewer");
296
+ const audience = requiredString(value.audience, "audience", configurationError);
297
+ if (audience !== "platform" && !audience.startsWith("dash:")) {
298
+ throw configurationError("audience must be platform or dash:<dash_id>");
299
+ }
300
+ if (value.template !== "read_only" && value.template !== "full" && value.template !== "custom") {
301
+ throw configurationError("template must be read_only, full or custom");
302
+ }
303
+ const permissions = [...new Set((value.permissions ?? []).map((item) => requiredString(item, "permission", configurationError)))];
304
+ if (value.template === "custom" && (permissions.length < 1 || permissions.length > 64)) {
305
+ throw configurationError("a custom template must name 1 to 64 permissions");
306
+ }
307
+ const dashIDs = [...new Set(value.dash_ids.map((item) => requiredString(item, "dash_id", configurationError)))];
308
+ if (dashIDs.length > 32 || dashIDs.includes("*")) throw configurationError("dash_ids must name at most 32 explicit Dashes");
309
+ if (audience.startsWith("dash:") && (dashIDs.length !== 1 || dashIDs[0] !== audience.slice(5))) {
310
+ throw configurationError("a Dash audience requires exactly its route Dash in dash_ids");
311
+ }
312
+ if (!Number.isSafeInteger(value.expires_in_days) || value.expires_in_days < 1 || value.expires_in_days > 30) {
313
+ throw configurationError("expires_in_days must be an integer from 1 to 30");
314
+ }
315
+ if (value.max_output_bytes !== void 0 && (!Number.isSafeInteger(value.max_output_bytes) || value.max_output_bytes < 1 || value.max_output_bytes > 1048576)) {
316
+ throw configurationError("max_output_bytes must be an integer from 1 to 1048576");
317
+ }
318
+ return {
319
+ name,
320
+ audience,
321
+ template: value.template,
322
+ ...value.template === "custom" ? { permissions } : {},
323
+ dash_ids: dashIDs,
324
+ expires_in_days: value.expires_in_days,
325
+ expected_version: version(value.expected_version),
326
+ reason: reason(value.reason),
327
+ ...value.max_output_bytes === void 0 ? {} : { max_output_bytes: value.max_output_bytes }
328
+ };
329
+ }
330
+ function createServiceAccountClient(options) {
331
+ const baseUrl = requiredString(options.baseUrl, "baseUrl", configurationError).replace(/\/+$/, "");
332
+ const transport = {
333
+ fetch: (input, init) => (options.fetch ?? globalThis.fetch)(input, init),
334
+ timeoutMs: positiveNumber(options.timeoutMs ?? 1e4, "timeoutMs", configurationError),
335
+ retry: {
336
+ attempts: nonNegativeInteger(options.retryAttempts ?? 1, "retryAttempts", configurationError),
337
+ maxDelayMs: positiveNumber(options.maxRetryDelayMs ?? 2e3, "maxRetryDelayMs", configurationError),
338
+ idempotentWrites: false
339
+ },
340
+ signal: options.signal
341
+ };
342
+ async function request(operation, path, decode, init = {}) {
343
+ const method = (init.method ?? "GET").toUpperCase();
344
+ const report = options.observe && ((event) => {
345
+ options.observe?.({ operation, ...event });
346
+ });
347
+ let headers;
348
+ try {
349
+ const accessToken = requiredString(await options.getAccessToken() ?? "", "access token", configurationError);
350
+ headers = new Headers(await options.getHeaders?.());
351
+ new Headers(init.headers).forEach((value, key) => headers.set(key, value));
352
+ headers.set("Authorization", `Bearer ${accessToken}`);
353
+ headers.set("Accept", "application/json");
354
+ if (init.body !== void 0) headers.set("Content-Type", "application/json");
355
+ } catch (error) {
356
+ try {
357
+ report?.({ method, outcome: "network_error", status: 0, requestId: "", durationMs: 0, attempts: 0 });
358
+ } catch {
359
+ }
360
+ throw error;
361
+ }
362
+ try {
363
+ const result = await performRequest(
364
+ transport,
365
+ `${baseUrl}${path}`,
366
+ { ...init, method, headers, cache: "no-store" },
367
+ report,
368
+ decode
369
+ );
370
+ return result.payload;
371
+ } catch (error) {
372
+ if (!isTransportError(error)) throw error;
373
+ const { outcome, status, code, message, requestId } = error.failure;
374
+ switch (outcome) {
375
+ case "timeout":
376
+ throw new ServiceAccountAPIError("Service Account request timed out", 0, "service_account_request_timeout", "");
377
+ case "cancelled":
378
+ throw new ServiceAccountAPIError("Service Account request was cancelled", 0, "service_account_request_cancelled", "");
379
+ case "network_error":
380
+ throw new ServiceAccountAPIError("Service Account service is unavailable", 0, "service_account_service_unavailable", "");
381
+ case "invalid_response":
382
+ throw new ServiceAccountAPIError("Service Account service returned an invalid response", status, "service_account_invalid_response", requestId);
383
+ case "api_error":
384
+ throw new ServiceAccountAPIError(message || code || "Service Account request failed", status, code, requestId);
385
+ }
386
+ }
387
+ }
388
+ function accountPath(serviceAccountID) {
389
+ return `${basePath}/${canonicalID(serviceAccountID, "serviceAccountId", uuidPattern)}`;
390
+ }
391
+ return {
392
+ list(params = {}) {
393
+ return request(
394
+ "platform.identity.service_accounts.list",
395
+ `${basePath}${listQuery(params)}`,
396
+ (payload) => parsePage(payload, parseServiceAccount)
397
+ );
398
+ },
399
+ get(serviceAccountID) {
400
+ return request(
401
+ "platform.identity.service_accounts.get",
402
+ accountPath(serviceAccountID),
403
+ parseServiceAccountEnvelope
404
+ );
405
+ },
406
+ create(input) {
407
+ return request(
408
+ "platform.identity.service_accounts.create",
409
+ basePath,
410
+ parseServiceAccountEnvelope,
411
+ { method: "POST", body: JSON.stringify(accountFields(input)) }
412
+ );
413
+ },
414
+ update(serviceAccountID, input) {
415
+ const fields = accountFields(input);
416
+ return request(
417
+ "platform.identity.service_accounts.update",
418
+ accountPath(serviceAccountID),
419
+ parseServiceAccountEnvelope,
420
+ {
421
+ method: "PUT",
422
+ body: JSON.stringify({ ...fields, enabled: input.enabled, expected_version: version(input.expected_version) })
423
+ }
424
+ );
425
+ },
426
+ listGrants(serviceAccountID) {
427
+ return request(
428
+ "platform.identity.service_accounts.grants.list",
429
+ `${accountPath(serviceAccountID)}/grants`,
430
+ (payload) => {
431
+ const page = objectValue(payload);
432
+ if (!Array.isArray(page.items)) invalidResponse();
433
+ return { items: page.items.map(parseGrant) };
434
+ }
435
+ );
436
+ },
437
+ replaceGrants(serviceAccountID, input) {
438
+ if (!Array.isArray(input.grants) || input.grants.length > 32) {
439
+ throw configurationError("grants must contain at most 32 entries");
440
+ }
441
+ return request(
442
+ "platform.identity.service_accounts.grants.replace",
443
+ `${accountPath(serviceAccountID)}/grants`,
444
+ parseServiceAccountEnvelope,
445
+ {
446
+ method: "PUT",
447
+ body: JSON.stringify({
448
+ grants: input.grants.map(grantInput),
449
+ expected_version: version(input.expected_version),
450
+ reason: reason(input.reason)
451
+ })
452
+ }
453
+ );
454
+ },
455
+ listCredentials(serviceAccountID, params = {}) {
456
+ return request(
457
+ "platform.identity.service_accounts.credentials.list",
458
+ `${accountPath(serviceAccountID)}/credentials${listQuery(params)}`,
459
+ (payload) => parsePage(payload, parseCredential)
460
+ );
461
+ },
462
+ mintCredential(serviceAccountID, input) {
463
+ return request(
464
+ "platform.identity.service_accounts.credentials.mint",
465
+ `${accountPath(serviceAccountID)}/credentials`,
466
+ parseMintedCredential,
467
+ { method: "POST", body: JSON.stringify(mintInput(input)) }
468
+ );
469
+ },
470
+ revokeCredential(serviceAccountID, credentialID, input) {
471
+ return request(
472
+ "platform.identity.service_accounts.credentials.revoke",
473
+ `${accountPath(serviceAccountID)}/credentials/${canonicalID(credentialID, "credentialId", credentialIDPattern)}`,
474
+ parseServiceAccountEnvelope,
475
+ {
476
+ method: "DELETE",
477
+ body: JSON.stringify({ expected_version: version(input.expected_version), reason: reason(input.reason) })
478
+ }
479
+ );
480
+ }
481
+ };
482
+ }
483
+
484
+ export { SERVICE_ACCOUNTS_MANAGE_PERMISSION, SERVICE_ACCOUNTS_VIEW_PERMISSION, ServiceAccountAPIError, createServiceAccountClient, isServiceAccountAPIError };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@c1m-public/platform-auth",
3
- "version": "0.12.0",
3
+ "version": "0.14.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "description": "Session and authorization helpers for C1M platform surfaces. The root is runtime-neutral (Web Request/Response): token/session reads, the first-party handoff (PKCE target + source), proxy session gate and coalesced refresh; ./next adds the server-only guard; ./access carries the resolved access snapshot, typed permission keys, predicates, a Next loader and React bindings",
@@ -20,9 +20,9 @@
20
20
  "types": "./dist/next.d.ts",
21
21
  "default": "./dist/next.js"
22
22
  },
23
- "./mcp-tokens": {
24
- "types": "./dist/mcp-tokens.d.ts",
25
- "default": "./dist/mcp-tokens.js"
23
+ "./service-accounts": {
24
+ "types": "./dist/service-accounts.d.ts",
25
+ "default": "./dist/service-accounts.js"
26
26
  },
27
27
  "./access": {
28
28
  "types": "./dist/access/index.d.ts",
@@ -1,79 +0,0 @@
1
- declare const MCP_TOOL_PERMISSIONS: readonly ["dash.domains.view", "dash.workspaces.view", "platform.audit.view", "platform.ops.manage", "platform.ops.view", "platform.tenants.view"];
2
- declare const MCP_WILDCARD_TOOL_PERMISSIONS: readonly ["dash.domains.view", "dash.workspaces.view", "platform.audit.view", "platform.ops.view", "platform.tenants.view"];
3
- type MCPToolPermission = (typeof MCP_TOOL_PERMISSIONS)[number];
4
-
5
- declare const MCP_ACCESS_PERMISSION: "platform.mcp.access";
6
- declare const MCP_TOKENS_MANAGE_PERMISSION: "platform.mcp.tokens.manage";
7
- declare const MCP_PERMISSION_WILDCARD: "*";
8
- type MCPTokenPermission = typeof MCP_ACCESS_PERMISSION | typeof MCP_PERMISSION_WILDCARD | MCPToolPermission;
9
- type MCPTokenOperation = "platform_user.auth.mcp_tokens.list" | "platform_user.auth.mcp_tokens.mint" | "platform_user.auth.mcp_tokens.revoke";
10
- type MCPTokenRequestOutcome = "success" | "api_error" | "network_error" | "timeout" | "invalid_response" | "cancelled";
11
- interface MCPTokenView {
12
- token_id: string;
13
- name: string;
14
- /** Recorded ceilings may include permissions added by a newer server. */
15
- permissions: string[];
16
- app_allowlist: string[];
17
- created_at: string;
18
- expires_at: string;
19
- last_used_at?: string;
20
- revoked_at?: string;
21
- }
22
- interface MCPTokenPage {
23
- items: MCPTokenView[];
24
- next_cursor?: string;
25
- has_more: boolean;
26
- mcp_enabled: boolean;
27
- }
28
- interface MCPTokenListParams {
29
- cursor?: string;
30
- limit?: number;
31
- }
32
- interface MintMCPTokenInput {
33
- name: string;
34
- expires_in_days: number;
35
- permissions: MCPTokenPermission[];
36
- app_allowlist: string[];
37
- }
38
- interface MintMCPTokenResponse {
39
- token: MCPTokenView;
40
- raw_token: string;
41
- }
42
- interface MCPTokenRequestObservation {
43
- operation: MCPTokenOperation;
44
- method: string;
45
- outcome: MCPTokenRequestOutcome;
46
- status: number;
47
- requestId: string;
48
- durationMs: number;
49
- attempts: number;
50
- }
51
- interface CreateMCPTokenClientOptions {
52
- baseUrl: string;
53
- getAccessToken: () => Promise<string | null | undefined> | string | null | undefined;
54
- getHeaders?: () => Promise<HeadersInit | undefined> | HeadersInit | undefined;
55
- fetch?: typeof globalThis.fetch;
56
- /** Per attempt (default 10000). */
57
- timeoutMs?: number;
58
- /** Additional attempts for GET only (default 1). Mint and revoke are never retried. */
59
- retryAttempts?: number;
60
- /** Cap on one retry delay (default 2000). */
61
- maxRetryDelayMs?: number;
62
- observe?: (event: MCPTokenRequestObservation) => void;
63
- signal?: AbortSignal;
64
- }
65
- declare class MCPTokenAPIError extends Error {
66
- readonly status: number;
67
- readonly code: string;
68
- readonly requestId: string;
69
- constructor(message: string, status: number, code: string, requestId: string);
70
- }
71
- declare function isMCPTokenAPIError(error: unknown): error is MCPTokenAPIError;
72
- declare function createMCPTokenClient(options: CreateMCPTokenClientOptions): {
73
- readonly list: (params?: MCPTokenListParams) => Promise<MCPTokenPage>;
74
- readonly mint: (input: MintMCPTokenInput) => Promise<MintMCPTokenResponse>;
75
- readonly revoke: (tokenId: string) => Promise<void>;
76
- };
77
- type MCPTokenClient = ReturnType<typeof createMCPTokenClient>;
78
-
79
- export { type CreateMCPTokenClientOptions, MCPTokenAPIError, type MCPTokenClient, type MCPTokenListParams, type MCPTokenOperation, type MCPTokenPage, type MCPTokenPermission, type MCPTokenRequestObservation, type MCPTokenRequestOutcome, type MCPTokenView, type MCPToolPermission, MCP_ACCESS_PERMISSION, MCP_PERMISSION_WILDCARD, MCP_TOKENS_MANAGE_PERMISSION, MCP_TOOL_PERMISSIONS, MCP_WILDCARD_TOOL_PERMISSIONS, type MintMCPTokenInput, type MintMCPTokenResponse, createMCPTokenClient, isMCPTokenAPIError };
@@ -1,357 +0,0 @@
1
- // ../transport/src/index.ts
2
- var RETRYABLE_STATUSES = /* @__PURE__ */ new Set([429, 502, 503, 504]);
3
- var TransportError = class extends Error {
4
- constructor(failure) {
5
- super(failure.message || failure.outcome);
6
- this.failure = failure;
7
- this.name = "TransportError";
8
- }
9
- failure;
10
- };
11
- function isTransportError(error) {
12
- return error instanceof TransportError || typeof error === "object" && error !== null && error.name === "TransportError";
13
- }
14
- function positiveNumber(value, label, fail) {
15
- if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) throw fail(`${label} must be a positive finite number`);
16
- return value;
17
- }
18
- function nonNegativeInteger(value, label, fail) {
19
- if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw fail(`${label} must be a non-negative safe integer`);
20
- return value;
21
- }
22
- function requiredString(value, label, fail) {
23
- const normalized = typeof value === "string" ? value.trim() : "";
24
- if (!normalized) throw fail(`${label} is required`);
25
- return normalized;
26
- }
27
- function backoffDelay(attempt, maxDelayMs) {
28
- const base = Math.min(250 * 2 ** Math.max(attempt, 0), maxDelayMs);
29
- return Math.floor(Math.random() * base);
30
- }
31
- function retryDelay(response, attempt, maxDelayMs) {
32
- const value = response.headers.get("Retry-After");
33
- if (!value) return backoffDelay(attempt, maxDelayMs);
34
- const seconds = Number(value);
35
- if (Number.isFinite(seconds)) return Math.min(Math.max(seconds * 1e3, 0), maxDelayMs);
36
- const date = Date.parse(value);
37
- return Number.isNaN(date) ? backoffDelay(attempt, maxDelayMs) : Math.min(Math.max(date - Date.now(), 0), maxDelayMs);
38
- }
39
- function wait(ms) {
40
- return ms <= 0 ? Promise.resolve() : new Promise((resolve) => setTimeout(resolve, ms));
41
- }
42
- function combineSignals(...signals) {
43
- const active = signals.filter((signal) => Boolean(signal));
44
- if (active.length === 0) return void 0;
45
- if (active.length === 1) return active[0];
46
- return AbortSignal.any(active);
47
- }
48
- function isRetryableRequest(method, headers, retry) {
49
- if (method === "GET") return true;
50
- return retry.idempotentWrites === true && headers.has("Idempotency-Key");
51
- }
52
- async function performRequest(transport, url, init, observe, decode) {
53
- const method = (init.method ?? "GET").toUpperCase();
54
- const headers = new Headers(init.headers);
55
- const startedAt = Date.now();
56
- const retryable = isRetryableRequest(method, headers, transport.retry);
57
- const maxAttempts = retryable ? transport.retry.attempts : 0;
58
- let attempts = 0;
59
- let status = 0;
60
- let requestId = "";
61
- let outcome = "network_error";
62
- const fail = (failure) => {
63
- outcome = failure.outcome;
64
- throw new TransportError({ requestId, ...failure });
65
- };
66
- try {
67
- let response;
68
- for (let attempt = 0; attempt <= maxAttempts; attempt += 1) {
69
- attempts = attempt + 1;
70
- const controller = new AbortController();
71
- const timeout = setTimeout(() => controller.abort(), transport.timeoutMs);
72
- try {
73
- response = await transport.fetch(url, {
74
- ...init,
75
- method,
76
- headers,
77
- signal: combineSignals(transport.signal, init.signal, controller.signal)
78
- });
79
- } catch {
80
- if (controller.signal.aborted) fail({ outcome: "timeout", status: 0, code: "", message: "" });
81
- if (transport.signal?.aborted || init.signal?.aborted) fail({ outcome: "cancelled", status: 0, code: "", message: "" });
82
- if (attempt < maxAttempts) {
83
- await wait(backoffDelay(attempt, transport.retry.maxDelayMs));
84
- continue;
85
- }
86
- fail({ outcome: "network_error", status: 0, code: "", message: "" });
87
- } finally {
88
- clearTimeout(timeout);
89
- }
90
- if (!RETRYABLE_STATUSES.has(response.status) || attempt === maxAttempts) break;
91
- await wait(retryDelay(response, attempt, transport.retry.maxDelayMs));
92
- }
93
- if (!response) return fail({ outcome: "network_error", status: 0, code: "", message: "" });
94
- status = response.status;
95
- requestId = response.headers.get("X-Request-ID") ?? "";
96
- if (!response.ok) {
97
- const envelope = await response.json().catch(() => ({}));
98
- if (typeof envelope.request_id === "string") requestId = envelope.request_id;
99
- return fail({
100
- outcome: "api_error",
101
- status,
102
- code: typeof envelope.code === "string" ? envelope.code : "",
103
- message: typeof envelope.message === "string" ? envelope.message : "",
104
- requestId
105
- });
106
- }
107
- let payload;
108
- try {
109
- if (status === 204) {
110
- payload = void 0;
111
- } else {
112
- const text = await response.text();
113
- const parsed = text ? JSON.parse(text) : void 0;
114
- payload = decode ? decode(parsed) : parsed;
115
- }
116
- } catch {
117
- return fail({ outcome: "invalid_response", status, code: "", message: "", requestId });
118
- }
119
- outcome = "success";
120
- return { payload, status, requestId };
121
- } finally {
122
- if (observe) {
123
- try {
124
- observe({ method, outcome, status, requestId, durationMs: Math.max(0, Date.now() - startedAt), attempts });
125
- } catch {
126
- }
127
- }
128
- }
129
- }
130
-
131
- // src/access/generated/mcp-tools.ts
132
- var MCP_TOOL_PERMISSIONS = [
133
- "dash.domains.view",
134
- "dash.workspaces.view",
135
- "platform.audit.view",
136
- "platform.ops.manage",
137
- "platform.ops.view",
138
- "platform.tenants.view"
139
- ];
140
- var MCP_WILDCARD_TOOL_PERMISSIONS = [
141
- "dash.domains.view",
142
- "dash.workspaces.view",
143
- "platform.audit.view",
144
- "platform.ops.view",
145
- "platform.tenants.view"
146
- ];
147
-
148
- // src/mcp-tokens.ts
149
- var MCP_ACCESS_PERMISSION = "platform.mcp.access";
150
- var MCP_TOKENS_MANAGE_PERMISSION = "platform.mcp.tokens.manage";
151
- var MCP_PERMISSION_WILDCARD = "*";
152
- var MCPTokenAPIError = class extends Error {
153
- constructor(message, status, code, requestId) {
154
- super(message);
155
- this.status = status;
156
- this.code = code;
157
- this.requestId = requestId;
158
- this.name = "MCPTokenAPIError";
159
- }
160
- status;
161
- code;
162
- requestId;
163
- };
164
- function isMCPTokenAPIError(error) {
165
- return error instanceof MCPTokenAPIError || typeof error === "object" && error !== null && error.name === "MCPTokenAPIError" && typeof error.status === "number" && typeof error.code === "string" && typeof error.requestId === "string";
166
- }
167
- var configurationError = (message) => new Error(message);
168
- var basePath = "/api/v1/platform/auth/me/mcp-tokens";
169
- var tokenIDPattern = /^[0-9a-f]{32}$/;
170
- var rawTokenPattern = /^sd_pat_([0-9a-f]{32})_[A-Za-z0-9_-]{43}$/;
171
- var timestampPattern = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;
172
- function invalidResponse() {
173
- throw new Error("invalid MCP token response");
174
- }
175
- function objectValue(value) {
176
- if (typeof value !== "object" || value === null || Array.isArray(value)) invalidResponse();
177
- return value;
178
- }
179
- function responseString(value, options = {}) {
180
- if (value === void 0 && options.optional) return void 0;
181
- if (typeof value !== "string" || value.length === 0) invalidResponse();
182
- if (options.tokenID && !tokenIDPattern.test(value)) invalidResponse();
183
- if (options.timestamp && (!timestampPattern.test(value) || !Number.isFinite(Date.parse(value)))) invalidResponse();
184
- return value;
185
- }
186
- function responseStrings(value) {
187
- if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string" || entry.length === 0)) invalidResponse();
188
- return [...value];
189
- }
190
- function parseMCPTokenView(value) {
191
- const item = objectValue(value);
192
- return {
193
- token_id: responseString(item.token_id, { tokenID: true }),
194
- name: responseString(item.name),
195
- permissions: responseStrings(item.permissions),
196
- app_allowlist: responseStrings(item.app_allowlist),
197
- created_at: responseString(item.created_at, { timestamp: true }),
198
- expires_at: responseString(item.expires_at, { timestamp: true }),
199
- last_used_at: responseString(item.last_used_at, { optional: true, timestamp: true }),
200
- revoked_at: responseString(item.revoked_at, { optional: true, timestamp: true })
201
- };
202
- }
203
- function parseMCPTokenPage(value) {
204
- const page = objectValue(value);
205
- if (!Array.isArray(page.items) || typeof page.has_more !== "boolean" || typeof page.mcp_enabled !== "boolean") invalidResponse();
206
- const nextCursor = responseString(page.next_cursor, { optional: true });
207
- if (Boolean(nextCursor) !== page.has_more) invalidResponse();
208
- return {
209
- items: page.items.map(parseMCPTokenView),
210
- next_cursor: nextCursor,
211
- has_more: page.has_more,
212
- mcp_enabled: page.mcp_enabled
213
- };
214
- }
215
- function parseMintMCPTokenResponse(value) {
216
- const response = objectValue(value);
217
- const token = parseMCPTokenView(response.token);
218
- const rawToken = responseString(response.raw_token);
219
- const match = rawToken.match(rawTokenPattern);
220
- if (!match || match[1] !== token.token_id) invalidResponse();
221
- return { token, raw_token: rawToken };
222
- }
223
- function normalizedStrings(values, label, max) {
224
- if (!Array.isArray(values)) throw configurationError(`${label} must be an array`);
225
- const normalized = [...new Set(values.map((value) => requiredString(value, label, configurationError)))];
226
- if (normalized.length > max) throw configurationError(`${label} must contain at most ${max} entries`);
227
- return normalized;
228
- }
229
- function mintInput(value) {
230
- const name = requiredString(value.name, "name", configurationError);
231
- if (name.length > 64) throw configurationError("name must be 64 characters or fewer");
232
- if (!Number.isSafeInteger(value.expires_in_days) || value.expires_in_days < 1 || value.expires_in_days > 90) {
233
- throw configurationError("expires_in_days must be an integer from 1 to 90");
234
- }
235
- const permissions = normalizedStrings(value.permissions, "permissions", 32);
236
- if (permissions.includes(MCP_PERMISSION_WILDCARD)) {
237
- if (permissions.length !== 1) {
238
- throw configurationError('permissions "*" must be the only entry');
239
- }
240
- } else {
241
- if (!permissions.includes(MCP_ACCESS_PERMISSION)) throw configurationError(`permissions must include ${MCP_ACCESS_PERMISSION}`);
242
- if (permissions.length < 2) throw configurationError("permissions must include at least one MCP tool permission");
243
- const allowedPermissions = /* @__PURE__ */ new Set([MCP_ACCESS_PERMISSION, ...MCP_TOOL_PERMISSIONS]);
244
- if (permissions.some((permission) => !allowedPermissions.has(permission))) {
245
- throw configurationError("permissions contains a key that is not available to MCP tools");
246
- }
247
- }
248
- const appAllowlist = normalizedStrings(value.app_allowlist, "app_allowlist", 32);
249
- if (appAllowlist.includes("*") && appAllowlist.length !== 1) {
250
- throw configurationError('app_allowlist "*" must be the only entry');
251
- }
252
- return {
253
- name,
254
- expires_in_days: value.expires_in_days,
255
- permissions,
256
- app_allowlist: appAllowlist
257
- };
258
- }
259
- function tokenIDInput(value) {
260
- const tokenID = requiredString(value, "tokenId", configurationError);
261
- if (!tokenIDPattern.test(tokenID)) throw configurationError("tokenId must be a 32-character hexadecimal MCP token id");
262
- return tokenID;
263
- }
264
- function createMCPTokenClient(options) {
265
- const baseUrl = requiredString(options.baseUrl, "baseUrl", configurationError).replace(/\/+$/, "");
266
- const transport = {
267
- fetch: (input, init) => (options.fetch ?? globalThis.fetch)(input, init),
268
- timeoutMs: positiveNumber(options.timeoutMs ?? 1e4, "timeoutMs", configurationError),
269
- retry: {
270
- attempts: nonNegativeInteger(options.retryAttempts ?? 1, "retryAttempts", configurationError),
271
- maxDelayMs: positiveNumber(options.maxRetryDelayMs ?? 2e3, "maxRetryDelayMs", configurationError),
272
- idempotentWrites: false
273
- },
274
- signal: options.signal
275
- };
276
- async function request(operation, path, decode, init = {}) {
277
- const method = (init.method ?? "GET").toUpperCase();
278
- const report = options.observe && ((event) => {
279
- options.observe?.({ operation, ...event });
280
- });
281
- let headers;
282
- try {
283
- const accessToken = requiredString(await options.getAccessToken() ?? "", "access token", configurationError);
284
- headers = new Headers(await options.getHeaders?.());
285
- new Headers(init.headers).forEach((value, key) => headers.set(key, value));
286
- headers.set("Authorization", `Bearer ${accessToken}`);
287
- headers.set("Accept", "application/json");
288
- if (init.body !== void 0) headers.set("Content-Type", "application/json");
289
- } catch (error) {
290
- try {
291
- report?.({ method, outcome: "network_error", status: 0, requestId: "", durationMs: 0, attempts: 0 });
292
- } catch {
293
- }
294
- throw error;
295
- }
296
- try {
297
- const result = await performRequest(
298
- transport,
299
- `${baseUrl}${path}`,
300
- { ...init, method, headers, cache: "no-store" },
301
- report,
302
- decode
303
- );
304
- return result.payload;
305
- } catch (error) {
306
- if (!isTransportError(error)) throw error;
307
- const { outcome, status, code, message, requestId } = error.failure;
308
- switch (outcome) {
309
- case "timeout":
310
- throw new MCPTokenAPIError("MCP token request timed out", 0, "mcp_token_request_timeout", "");
311
- case "cancelled":
312
- throw new MCPTokenAPIError("MCP token request was cancelled", 0, "mcp_token_request_cancelled", "");
313
- case "network_error":
314
- throw new MCPTokenAPIError("MCP token service is unavailable", 0, "mcp_token_service_unavailable", "");
315
- case "invalid_response":
316
- throw new MCPTokenAPIError("MCP token service returned an invalid response", status, "mcp_token_invalid_response", requestId);
317
- case "api_error":
318
- throw new MCPTokenAPIError(message || code || "MCP token request failed", status, code, requestId);
319
- }
320
- }
321
- }
322
- return {
323
- list(params = {}) {
324
- const query = new URLSearchParams();
325
- const cursor = params.cursor?.trim();
326
- if (cursor) query.set("cursor", cursor);
327
- if (params.limit !== void 0) {
328
- const limit = positiveNumber(params.limit, "limit", configurationError);
329
- if (!Number.isSafeInteger(limit) || limit > 100) throw configurationError("limit must be an integer from 1 to 100");
330
- query.set("limit", String(limit));
331
- }
332
- return request(
333
- "platform_user.auth.mcp_tokens.list",
334
- `${basePath}${query.size ? `?${query}` : ""}`,
335
- parseMCPTokenPage
336
- );
337
- },
338
- mint(input) {
339
- return request("platform_user.auth.mcp_tokens.mint", basePath, parseMintMCPTokenResponse, {
340
- method: "POST",
341
- body: JSON.stringify(mintInput(input))
342
- });
343
- },
344
- revoke(tokenId) {
345
- return request(
346
- "platform_user.auth.mcp_tokens.revoke",
347
- `${basePath}/${tokenIDInput(tokenId)}`,
348
- (payload) => {
349
- if (payload !== void 0) invalidResponse();
350
- },
351
- { method: "DELETE" }
352
- );
353
- }
354
- };
355
- }
356
-
357
- export { MCPTokenAPIError, MCP_ACCESS_PERMISSION, MCP_PERMISSION_WILDCARD, MCP_TOKENS_MANAGE_PERMISSION, MCP_TOOL_PERMISSIONS, MCP_WILDCARD_TOOL_PERMISSIONS, createMCPTokenClient, isMCPTokenAPIError };