@c1m-public/platform-auth 0.17.0 → 0.19.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 +1 -25
- package/dist/access/index.d.ts +1 -1
- package/dist/access/index.js +12 -4
- package/dist/access/next.d.ts +2 -2
- package/dist/access/next.js +12 -4
- package/dist/{index-BoZch6LF.d.ts → index-BPDwOudu.d.ts} +2 -2
- package/dist/{index-Blx3FNX2.d.ts → index-BxyVV6Wt.d.ts} +2 -4
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/next.d.ts +6 -10
- package/dist/next.js +1 -1
- package/package.json +1 -5
- package/dist/service-accounts.d.ts +0 -149
- package/dist/service-accounts.js +0 -486
package/README.md
CHANGED
|
@@ -11,7 +11,6 @@ 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
|
-
./service-accounts operator-owned service accounts and credentials (framework-neutral)
|
|
15
14
|
./access authorization: snapshot, keys, predicates (framework-neutral)
|
|
16
15
|
./access/next access loader: require / forbidden / invalidate (Next, server-only)
|
|
17
16
|
./access/react <Can>, useCan, AccessProvider (client)
|
|
@@ -20,34 +19,11 @@ need — the boundary is the subpath.
|
|
|
20
19
|
`next` and `react` are **optional** peer dependencies: a BFF that only reads
|
|
21
20
|
sessions never needs them.
|
|
22
21
|
|
|
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.
|
|
45
|
-
|
|
46
22
|
## `.` — session
|
|
47
23
|
|
|
48
24
|
| Export | Purpose |
|
|
49
25
|
|---|---|
|
|
50
|
-
| `decodeTokenPayload`, `decodeDefaultSession`, `hasTokenAudience`, `isTokenExpired`, `isTokenExpiringSoon`, `tokenMaxAgeSeconds` | Read an access token for routing. Decoding is **not** verification — the backend re-verifies every call. `decodeDefaultSession` prefers `
|
|
26
|
+
| `decodeTokenPayload`, `decodeDefaultSession`, `hasTokenAudience`, `isTokenExpired`, `isTokenExpiringSoon`, `tokenMaxAgeSeconds` | Read an access token for routing. Decoding is **not** verification — the backend re-verifies every call. `decodeDefaultSession` prefers `impersonation_target`, so a support session resolves as the impersonated user. |
|
|
51
27
|
| `parseAuthResponse`, `AuthResponse` | Validate a backend auth envelope before trusting it. |
|
|
52
28
|
| `readCookie`, `serializeCookie`, `setCookie`, `deleteCookie` | Cookie helpers over Web `Request`/`Response`. `__Host-` names get `Secure` automatically. |
|
|
53
29
|
| `createDeviceIdentity` | The `X-Client-Device-ID` cookie the backend requires to create a session. |
|
package/dist/access/index.d.ts
CHANGED
|
@@ -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-
|
|
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-BPDwOudu.js';
|
package/dist/access/index.js
CHANGED
|
@@ -10,12 +10,18 @@ var PLATFORM_PERMISSIONS = [
|
|
|
10
10
|
"linkservice.qr.manage",
|
|
11
11
|
"linkservice.view",
|
|
12
12
|
"platform.admin.view",
|
|
13
|
+
"platform.audience.manage",
|
|
14
|
+
"platform.audience.view",
|
|
13
15
|
"platform.audit.view",
|
|
14
16
|
"platform.auth.manage",
|
|
15
17
|
"platform.billing.manage",
|
|
16
18
|
"platform.billing.view",
|
|
17
19
|
"platform.channels.manage",
|
|
18
20
|
"platform.channels.view",
|
|
21
|
+
"platform.communications.content.view",
|
|
22
|
+
"platform.communications.manage",
|
|
23
|
+
"platform.communications.send",
|
|
24
|
+
"platform.communications.view",
|
|
19
25
|
"platform.config.manage",
|
|
20
26
|
"platform.dashes.archive",
|
|
21
27
|
"platform.dashes.manage",
|
|
@@ -30,18 +36,17 @@ var PLATFORM_PERMISSIONS = [
|
|
|
30
36
|
"platform.offboarding.view",
|
|
31
37
|
"platform.ops.manage",
|
|
32
38
|
"platform.ops.view",
|
|
39
|
+
"platform.ownership.transfer",
|
|
33
40
|
"platform.service_accounts.manage",
|
|
34
41
|
"platform.service_accounts.view",
|
|
35
42
|
"platform.support.impersonate",
|
|
43
|
+
"platform.support.impersonation.delegate",
|
|
36
44
|
"platform.support.sessions",
|
|
37
|
-
"platform.tenants.archive",
|
|
38
|
-
"platform.tenants.manage",
|
|
39
|
-
"platform.tenants.restore",
|
|
40
|
-
"platform.tenants.view",
|
|
41
45
|
"platform.users.deactivate",
|
|
42
46
|
"platform.users.delete",
|
|
43
47
|
"platform.users.invite",
|
|
44
48
|
"platform.users.manage_access",
|
|
49
|
+
"platform.users.manage_profile",
|
|
45
50
|
"platform.users.reactivate",
|
|
46
51
|
"platform.users.view"
|
|
47
52
|
];
|
|
@@ -96,9 +101,12 @@ var WORKSPACE_PERMISSIONS = [
|
|
|
96
101
|
"workspace.crm.view",
|
|
97
102
|
"workspace.customers.manage",
|
|
98
103
|
"workspace.customers.view",
|
|
104
|
+
"workspace.drafts.delete",
|
|
105
|
+
"workspace.lifecycle.manage",
|
|
99
106
|
"workspace.orders.manage",
|
|
100
107
|
"workspace.orders.view",
|
|
101
108
|
"workspace.payments.record",
|
|
109
|
+
"workspace.payments.refund",
|
|
102
110
|
"workspace.site.edit",
|
|
103
111
|
"workspace.site.view",
|
|
104
112
|
"workspace.staff.manage"
|
package/dist/access/next.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as AccessSnapshot, P as PermissionCheckOptions, R as Resolvable } from '../index-
|
|
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-
|
|
1
|
+
import { A as AccessSnapshot, P as PermissionCheckOptions, R as Resolvable } from '../index-BPDwOudu.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-BPDwOudu.js';
|
|
3
3
|
|
|
4
4
|
/** Default cache tag for one subject's snapshot: `access:<subjectId>`. */
|
|
5
5
|
declare function accessCacheTag(subjectId: string): string;
|
package/dist/access/next.js
CHANGED
|
@@ -268,12 +268,18 @@ var PLATFORM_PERMISSIONS = [
|
|
|
268
268
|
"linkservice.qr.manage",
|
|
269
269
|
"linkservice.view",
|
|
270
270
|
"platform.admin.view",
|
|
271
|
+
"platform.audience.manage",
|
|
272
|
+
"platform.audience.view",
|
|
271
273
|
"platform.audit.view",
|
|
272
274
|
"platform.auth.manage",
|
|
273
275
|
"platform.billing.manage",
|
|
274
276
|
"platform.billing.view",
|
|
275
277
|
"platform.channels.manage",
|
|
276
278
|
"platform.channels.view",
|
|
279
|
+
"platform.communications.content.view",
|
|
280
|
+
"platform.communications.manage",
|
|
281
|
+
"platform.communications.send",
|
|
282
|
+
"platform.communications.view",
|
|
277
283
|
"platform.config.manage",
|
|
278
284
|
"platform.dashes.archive",
|
|
279
285
|
"platform.dashes.manage",
|
|
@@ -288,18 +294,17 @@ var PLATFORM_PERMISSIONS = [
|
|
|
288
294
|
"platform.offboarding.view",
|
|
289
295
|
"platform.ops.manage",
|
|
290
296
|
"platform.ops.view",
|
|
297
|
+
"platform.ownership.transfer",
|
|
291
298
|
"platform.service_accounts.manage",
|
|
292
299
|
"platform.service_accounts.view",
|
|
293
300
|
"platform.support.impersonate",
|
|
301
|
+
"platform.support.impersonation.delegate",
|
|
294
302
|
"platform.support.sessions",
|
|
295
|
-
"platform.tenants.archive",
|
|
296
|
-
"platform.tenants.manage",
|
|
297
|
-
"platform.tenants.restore",
|
|
298
|
-
"platform.tenants.view",
|
|
299
303
|
"platform.users.deactivate",
|
|
300
304
|
"platform.users.delete",
|
|
301
305
|
"platform.users.invite",
|
|
302
306
|
"platform.users.manage_access",
|
|
307
|
+
"platform.users.manage_profile",
|
|
303
308
|
"platform.users.reactivate",
|
|
304
309
|
"platform.users.view"
|
|
305
310
|
];
|
|
@@ -354,9 +359,12 @@ var WORKSPACE_PERMISSIONS = [
|
|
|
354
359
|
"workspace.crm.view",
|
|
355
360
|
"workspace.customers.manage",
|
|
356
361
|
"workspace.customers.view",
|
|
362
|
+
"workspace.drafts.delete",
|
|
363
|
+
"workspace.lifecycle.manage",
|
|
357
364
|
"workspace.orders.manage",
|
|
358
365
|
"workspace.orders.view",
|
|
359
366
|
"workspace.payments.record",
|
|
367
|
+
"workspace.payments.refund",
|
|
360
368
|
"workspace.site.edit",
|
|
361
369
|
"workspace.site.view",
|
|
362
370
|
"workspace.staff.manage"
|
|
@@ -1,5 +1,5 @@
|
|
|
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.dashes.archive", "platform.dashes.manage", "platform.dashes.purge", "platform.dashes.restore", "platform.dashes.view", "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.
|
|
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.audience.manage", "platform.audience.view", "platform.audit.view", "platform.auth.manage", "platform.billing.manage", "platform.billing.view", "platform.channels.manage", "platform.channels.view", "platform.communications.content.view", "platform.communications.manage", "platform.communications.send", "platform.communications.view", "platform.config.manage", "platform.dashes.archive", "platform.dashes.manage", "platform.dashes.purge", "platform.dashes.restore", "platform.dashes.view", "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.ownership.transfer", "platform.service_accounts.manage", "platform.service_accounts.view", "platform.support.impersonate", "platform.support.impersonation.delegate", "platform.support.sessions", "platform.users.deactivate", "platform.users.delete", "platform.users.invite", "platform.users.manage_access", "platform.users.manage_profile", "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
5
|
declare const DASH_PERMISSIONS: readonly ["dash.activity.view", "dash.apps.manage", "dash.apps.view", "dash.billing.manage", "dash.billing.view", "dash.channels.manage", "dash.customers.manage", "dash.customers.view", "dash.domains.manage", "dash.domains.view", "dash.leads.export", "dash.leads.view", "dash.learning.records.view", "dash.learning.view", "dash.marketing.view", "dash.mcp.access", "dash.members.manage", "dash.members.view", "dash.ops_library.view", "dash.overview.view", "dash.ownership.transfer", "dash.plans.manage", "dash.plans.view", "dash.publish", "dash.settings.manage", "dash.settings.view", "dash.shop.view", "dash.workspaces.admin", "dash.workspaces.manage", "dash.workspaces.view"];
|
|
@@ -11,7 +11,7 @@ type DashRole = (typeof DASH_ROLES)[number];
|
|
|
11
11
|
declare const LEADBROKER_PERMISSIONS: readonly ["leadbroker.finance.manage", "leadbroker.leads.dispatch", "leadbroker.leads.review", "leadbroker.leads.view", "leadbroker.policy.manage"];
|
|
12
12
|
type LeadBrokerPermissionKey = (typeof LEADBROKER_PERMISSIONS)[number];
|
|
13
13
|
/** Workspace-staff permission keys. */
|
|
14
|
-
declare const WORKSPACE_PERMISSIONS: readonly ["workspace.channels.manage", "workspace.channels.secrets", "workspace.channels.view", "workspace.crm.manage", "workspace.crm.view", "workspace.customers.manage", "workspace.customers.view", "workspace.orders.manage", "workspace.orders.view", "workspace.payments.record", "workspace.site.edit", "workspace.site.view", "workspace.staff.manage"];
|
|
14
|
+
declare const WORKSPACE_PERMISSIONS: readonly ["workspace.channels.manage", "workspace.channels.secrets", "workspace.channels.view", "workspace.crm.manage", "workspace.crm.view", "workspace.customers.manage", "workspace.customers.view", "workspace.drafts.delete", "workspace.lifecycle.manage", "workspace.orders.manage", "workspace.orders.view", "workspace.payments.record", "workspace.payments.refund", "workspace.site.edit", "workspace.site.view", "workspace.staff.manage"];
|
|
15
15
|
type WorkspacePermissionKey = (typeof WORKSPACE_PERMISSIONS)[number];
|
|
16
16
|
/** Assignable workspace-staff role bundles (grant keys at workspace scope). */
|
|
17
17
|
declare const WORKSPACE_ROLES: readonly ["workspace.editor", "workspace.frontdesk", "workspace.manager"];
|
|
@@ -20,7 +20,7 @@ type TokenPayload = Record<string, unknown> & {
|
|
|
20
20
|
exp?: number;
|
|
21
21
|
iat?: number;
|
|
22
22
|
actor_id?: string;
|
|
23
|
-
|
|
23
|
+
impersonation_target?: string;
|
|
24
24
|
customer_id?: string;
|
|
25
25
|
user_id?: string;
|
|
26
26
|
aud?: string | string[];
|
|
@@ -184,9 +184,7 @@ interface RefreshedSession {
|
|
|
184
184
|
* `rejected` and `unavailable` must never be merged. A caller acts on them
|
|
185
185
|
* oppositely: a rejected token means clear the cookies and send the user to
|
|
186
186
|
* log in; an unreachable backend means keep the cookies and say "try again".
|
|
187
|
-
*
|
|
188
|
-
* SaaSDash — and because the cookies were cleared, they stayed out after the
|
|
189
|
-
* backend came back. `refresh()` cannot express this (a truthy failure object
|
|
187
|
+
* `refresh()` cannot express this (a truthy failure object
|
|
190
188
|
* would break every `if (refreshed)` caller), so the distinction lives here.
|
|
191
189
|
*/
|
|
192
190
|
type RefreshOutcome = {
|
package/dist/index.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { a as AUTH_ERROR_MESSAGES, b as AuthResponse, C as CookieOptions, D as DeviceIdentity, c as DeviceIdentityConfig, d as DeviceIdentityStore, H as HANDOFF_ERROR_FALLBACK, e as HANDOFF_ERROR_MESSAGES, f as HandoffSource, g as HandoffSourceConfig, h as HandoffSourceTarget, i as HandoffTarget, j as HandoffTargetConfig, k as RefreshOutcome, l as RefreshedSession, m as SSO_ERROR_MESSAGES, S as SessionData, n as SessionGateDecision, o as SessionGateInput, p as SessionRefresher, q as SessionRefresherConfig, r as SessionUser, T as TokenPayload, s as applyForwardedClientHeaders, t as authErrorMessage, u as brokerPaths, v as createDeviceIdentity, w as createHandoffSource, x as createHandoffTarget, y as createSessionRefresher, z as decodeBase64Url, B as decodeDefaultSession, E as decodeTokenPayload, F as deleteCookie, G as evaluateSessionGate, I as forwardedRequestHeaders, J as handoffErrorMessage, K as hasSessionShape, L as hasTokenAudience, M as isAuthErrorCode, N as isHandoffErrorCode, O as isTokenExpired, P as isTokenExpiringSoon, Q as parseAuthResponse, U as parseRefreshEnvelope, V as readCookie, W as safeInternalPath, X as serializeCookie, Y as setCookie, Z as sourceStartPath, _ as tokenMaxAgeSeconds } from './index-
|
|
1
|
+
export { a as AUTH_ERROR_MESSAGES, b as AuthResponse, C as CookieOptions, D as DeviceIdentity, c as DeviceIdentityConfig, d as DeviceIdentityStore, H as HANDOFF_ERROR_FALLBACK, e as HANDOFF_ERROR_MESSAGES, f as HandoffSource, g as HandoffSourceConfig, h as HandoffSourceTarget, i as HandoffTarget, j as HandoffTargetConfig, k as RefreshOutcome, l as RefreshedSession, m as SSO_ERROR_MESSAGES, S as SessionData, n as SessionGateDecision, o as SessionGateInput, p as SessionRefresher, q as SessionRefresherConfig, r as SessionUser, T as TokenPayload, s as applyForwardedClientHeaders, t as authErrorMessage, u as brokerPaths, v as createDeviceIdentity, w as createHandoffSource, x as createHandoffTarget, y as createSessionRefresher, z as decodeBase64Url, B as decodeDefaultSession, E as decodeTokenPayload, F as deleteCookie, G as evaluateSessionGate, I as forwardedRequestHeaders, J as handoffErrorMessage, K as hasSessionShape, L as hasTokenAudience, M as isAuthErrorCode, N as isHandoffErrorCode, O as isTokenExpired, P as isTokenExpiringSoon, Q as parseAuthResponse, U as parseRefreshEnvelope, V as readCookie, W as safeInternalPath, X as serializeCookie, Y as setCookie, Z as sourceStartPath, _ as tokenMaxAgeSeconds } from './index-BxyVV6Wt.js';
|
package/dist/index.js
CHANGED
|
@@ -53,7 +53,7 @@ function isTokenExpiringSoon(token, bufferSeconds = 120) {
|
|
|
53
53
|
function decodeDefaultSession(token) {
|
|
54
54
|
const decoded = decodeTokenPayload(token);
|
|
55
55
|
if (!decoded) return null;
|
|
56
|
-
const actorId = decoded.
|
|
56
|
+
const actorId = decoded.impersonation_target || decoded.actor_id || decoded.customer_id || decoded.user_id || (typeof decoded.sub === "string" ? decoded.sub : void 0);
|
|
57
57
|
if (!actorId) return null;
|
|
58
58
|
return {
|
|
59
59
|
user: {
|
package/dist/next.d.ts
CHANGED
|
@@ -1,11 +1,9 @@
|
|
|
1
|
-
import { R as Resolvable, A as AsyncResolvable, S as SessionData, C as CookieOptions } from './index-
|
|
2
|
-
export { a as AUTH_ERROR_MESSAGES, b as AuthResponse, D as DeviceIdentity, c as DeviceIdentityConfig, d as DeviceIdentityStore, H as HANDOFF_ERROR_FALLBACK, e as HANDOFF_ERROR_MESSAGES, f as HandoffSource, g as HandoffSourceConfig, h as HandoffSourceTarget, i as HandoffTarget, j as HandoffTargetConfig, k as RefreshOutcome, l as RefreshedSession, m as SSO_ERROR_MESSAGES, n as SessionGateDecision, o as SessionGateInput, p as SessionRefresher, q as SessionRefresherConfig, r as SessionUser, T as TokenPayload, s as applyForwardedClientHeaders, t as authErrorMessage, u as brokerPaths, v as createDeviceIdentity, w as createHandoffSource, x as createHandoffTarget, y as createSessionRefresher, z as decodeBase64Url, B as decodeDefaultSession, E as decodeTokenPayload, F as deleteCookie, G as evaluateSessionGate, I as forwardedRequestHeaders, J as handoffErrorMessage, K as hasSessionShape, L as hasTokenAudience, M as isAuthErrorCode, N as isHandoffErrorCode, O as isTokenExpired, P as isTokenExpiringSoon, Q as parseAuthResponse, U as parseRefreshEnvelope, V as readCookie, W as safeInternalPath, X as serializeCookie, Y as setCookie, Z as sourceStartPath, _ as tokenMaxAgeSeconds } from './index-
|
|
1
|
+
import { R as Resolvable, A as AsyncResolvable, S as SessionData, C as CookieOptions } from './index-BxyVV6Wt.js';
|
|
2
|
+
export { a as AUTH_ERROR_MESSAGES, b as AuthResponse, D as DeviceIdentity, c as DeviceIdentityConfig, d as DeviceIdentityStore, H as HANDOFF_ERROR_FALLBACK, e as HANDOFF_ERROR_MESSAGES, f as HandoffSource, g as HandoffSourceConfig, h as HandoffSourceTarget, i as HandoffTarget, j as HandoffTargetConfig, k as RefreshOutcome, l as RefreshedSession, m as SSO_ERROR_MESSAGES, n as SessionGateDecision, o as SessionGateInput, p as SessionRefresher, q as SessionRefresherConfig, r as SessionUser, T as TokenPayload, s as applyForwardedClientHeaders, t as authErrorMessage, u as brokerPaths, v as createDeviceIdentity, w as createHandoffSource, x as createHandoffTarget, y as createSessionRefresher, z as decodeBase64Url, B as decodeDefaultSession, E as decodeTokenPayload, F as deleteCookie, G as evaluateSessionGate, I as forwardedRequestHeaders, J as handoffErrorMessage, K as hasSessionShape, L as hasTokenAudience, M as isAuthErrorCode, N as isHandoffErrorCode, O as isTokenExpired, P as isTokenExpiringSoon, Q as parseAuthResponse, U as parseRefreshEnvelope, V as readCookie, W as safeInternalPath, X as serializeCookie, Y as setCookie, Z as sourceStartPath, _ as tokenMaxAgeSeconds } from './index-BxyVV6Wt.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
|
-
* The error vocabulary every first-party platform surface uses at its edge
|
|
6
|
-
*
|
|
7
|
-
* each carried a private copy of these classes; they are the same four
|
|
8
|
-
* everywhere because the backend's 401 codes are the same everywhere.
|
|
5
|
+
* The error vocabulary every first-party platform surface uses at its edge,
|
|
6
|
+
* mirroring the backend's 401 codes.
|
|
9
7
|
*/
|
|
10
8
|
declare class SessionExpiredError extends Error {
|
|
11
9
|
constructor();
|
|
@@ -132,11 +130,9 @@ interface SessionWriteOptions {
|
|
|
132
130
|
cookieDomain?: string;
|
|
133
131
|
}
|
|
134
132
|
/**
|
|
135
|
-
* Session cookies for a first-party Next.js platform surface
|
|
133
|
+
* Session cookies for a first-party Next.js platform surface.
|
|
136
134
|
*
|
|
137
|
-
*
|
|
138
|
-
* shared-auth), the Affiliate Portal and the Knowledge Library — around the
|
|
139
|
-
* same primitives, with the same three cookies and the same rules:
|
|
135
|
+
* Three cookies, with these rules:
|
|
140
136
|
*
|
|
141
137
|
* - rememberMe=false → no Max-Age, so the cookies die with the browser; true →
|
|
142
138
|
* the configured cap, shortened to the token's own expiry.
|
package/dist/next.js
CHANGED
|
@@ -58,7 +58,7 @@ function isTokenExpiringSoon(token, bufferSeconds = 120) {
|
|
|
58
58
|
function decodeDefaultSession(token) {
|
|
59
59
|
const decoded = decodeTokenPayload(token);
|
|
60
60
|
if (!decoded) return null;
|
|
61
|
-
const actorId = decoded.
|
|
61
|
+
const actorId = decoded.impersonation_target || decoded.actor_id || decoded.customer_id || decoded.user_id || (typeof decoded.sub === "string" ? decoded.sub : void 0);
|
|
62
62
|
if (!actorId) return null;
|
|
63
63
|
return {
|
|
64
64
|
user: {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@c1m-public/platform-auth",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.19.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,10 +20,6 @@
|
|
|
20
20
|
"types": "./dist/next.d.ts",
|
|
21
21
|
"default": "./dist/next.js"
|
|
22
22
|
},
|
|
23
|
-
"./service-accounts": {
|
|
24
|
-
"types": "./dist/service-accounts.d.ts",
|
|
25
|
-
"default": "./dist/service-accounts.js"
|
|
26
|
-
},
|
|
27
23
|
"./access": {
|
|
28
24
|
"types": "./dist/access/index.d.ts",
|
|
29
25
|
"default": "./dist/access/index.js"
|
|
@@ -1,149 +0,0 @@
|
|
|
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 };
|
package/dist/service-accounts.js
DELETED
|
@@ -1,486 +0,0 @@
|
|
|
1
|
-
// ../resilience/src/index.ts
|
|
2
|
-
var RETRYABLE_STATUSES = /* @__PURE__ */ new Set([429, 502, 503, 504]);
|
|
3
|
-
function backoffDelay(attempt, maxDelayMs) {
|
|
4
|
-
const base = Math.min(250 * 2 ** Math.max(attempt, 0), maxDelayMs);
|
|
5
|
-
return Math.floor(Math.random() * base);
|
|
6
|
-
}
|
|
7
|
-
function retryDelay(response, attempt, maxDelayMs) {
|
|
8
|
-
const value = response.headers.get("Retry-After");
|
|
9
|
-
if (!value) return backoffDelay(attempt, maxDelayMs);
|
|
10
|
-
const seconds = Number(value);
|
|
11
|
-
if (Number.isFinite(seconds)) return Math.min(Math.max(seconds * 1e3, 0), maxDelayMs);
|
|
12
|
-
const date = Date.parse(value);
|
|
13
|
-
return Number.isNaN(date) ? backoffDelay(attempt, maxDelayMs) : Math.min(Math.max(date - Date.now(), 0), maxDelayMs);
|
|
14
|
-
}
|
|
15
|
-
function wait(ms) {
|
|
16
|
-
return ms <= 0 ? Promise.resolve() : new Promise((resolve) => setTimeout(resolve, ms));
|
|
17
|
-
}
|
|
18
|
-
function combineSignals(...signals) {
|
|
19
|
-
const active = signals.filter((signal) => Boolean(signal));
|
|
20
|
-
if (active.length === 0) return void 0;
|
|
21
|
-
if (active.length === 1) return active[0];
|
|
22
|
-
return AbortSignal.any(active);
|
|
23
|
-
}
|
|
24
|
-
function isRetryableRequest(method, headers, retry) {
|
|
25
|
-
if (method === "GET") return true;
|
|
26
|
-
return retry.idempotentWrites === true && headers.has("Idempotency-Key");
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
// ../transport/src/index.ts
|
|
30
|
-
var TransportError = class extends Error {
|
|
31
|
-
constructor(failure) {
|
|
32
|
-
super(failure.message || failure.outcome);
|
|
33
|
-
this.failure = failure;
|
|
34
|
-
this.name = "TransportError";
|
|
35
|
-
}
|
|
36
|
-
failure;
|
|
37
|
-
};
|
|
38
|
-
function isTransportError(error) {
|
|
39
|
-
return error instanceof TransportError || typeof error === "object" && error !== null && error.name === "TransportError";
|
|
40
|
-
}
|
|
41
|
-
function positiveNumber(value, label, fail) {
|
|
42
|
-
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) throw fail(`${label} must be a positive finite number`);
|
|
43
|
-
return value;
|
|
44
|
-
}
|
|
45
|
-
function nonNegativeInteger(value, label, fail) {
|
|
46
|
-
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw fail(`${label} must be a non-negative safe integer`);
|
|
47
|
-
return value;
|
|
48
|
-
}
|
|
49
|
-
function requiredString(value, label, fail) {
|
|
50
|
-
const normalized = typeof value === "string" ? value.trim() : "";
|
|
51
|
-
if (!normalized) throw fail(`${label} is required`);
|
|
52
|
-
return normalized;
|
|
53
|
-
}
|
|
54
|
-
async function performRequest(transport, url, init, observe, decode) {
|
|
55
|
-
const method = (init.method ?? "GET").toUpperCase();
|
|
56
|
-
const headers = new Headers(init.headers);
|
|
57
|
-
const startedAt = Date.now();
|
|
58
|
-
const retryable = isRetryableRequest(method, headers, transport.retry);
|
|
59
|
-
const maxAttempts = retryable ? transport.retry.attempts : 0;
|
|
60
|
-
let attempts = 0;
|
|
61
|
-
let status = 0;
|
|
62
|
-
let requestId = "";
|
|
63
|
-
let outcome = "network_error";
|
|
64
|
-
const fail = (failure) => {
|
|
65
|
-
outcome = failure.outcome;
|
|
66
|
-
throw new TransportError({ requestId, ...failure });
|
|
67
|
-
};
|
|
68
|
-
try {
|
|
69
|
-
let response;
|
|
70
|
-
for (let attempt = 0; attempt <= maxAttempts; attempt += 1) {
|
|
71
|
-
attempts = attempt + 1;
|
|
72
|
-
const controller = new AbortController();
|
|
73
|
-
const timeout = setTimeout(() => controller.abort(), transport.timeoutMs);
|
|
74
|
-
try {
|
|
75
|
-
response = await transport.fetch(url, {
|
|
76
|
-
...init,
|
|
77
|
-
method,
|
|
78
|
-
headers,
|
|
79
|
-
signal: combineSignals(transport.signal, init.signal, controller.signal)
|
|
80
|
-
});
|
|
81
|
-
} catch {
|
|
82
|
-
if (controller.signal.aborted) fail({ outcome: "timeout", status: 0, code: "", message: "" });
|
|
83
|
-
if (transport.signal?.aborted || init.signal?.aborted) fail({ outcome: "cancelled", status: 0, code: "", message: "" });
|
|
84
|
-
if (attempt < maxAttempts) {
|
|
85
|
-
await wait(backoffDelay(attempt, transport.retry.maxDelayMs));
|
|
86
|
-
continue;
|
|
87
|
-
}
|
|
88
|
-
fail({ outcome: "network_error", status: 0, code: "", message: "" });
|
|
89
|
-
} finally {
|
|
90
|
-
clearTimeout(timeout);
|
|
91
|
-
}
|
|
92
|
-
if (!RETRYABLE_STATUSES.has(response.status) || attempt === maxAttempts) break;
|
|
93
|
-
await wait(retryDelay(response, attempt, transport.retry.maxDelayMs));
|
|
94
|
-
}
|
|
95
|
-
if (!response) return fail({ outcome: "network_error", status: 0, code: "", message: "" });
|
|
96
|
-
status = response.status;
|
|
97
|
-
requestId = response.headers.get("X-Request-ID") ?? "";
|
|
98
|
-
if (!response.ok) {
|
|
99
|
-
const envelope = await response.json().catch(() => ({}));
|
|
100
|
-
if (typeof envelope.request_id === "string") requestId = envelope.request_id;
|
|
101
|
-
return fail({
|
|
102
|
-
outcome: "api_error",
|
|
103
|
-
status,
|
|
104
|
-
code: typeof envelope.code === "string" ? envelope.code : "",
|
|
105
|
-
message: typeof envelope.message === "string" ? envelope.message : "",
|
|
106
|
-
requestId
|
|
107
|
-
});
|
|
108
|
-
}
|
|
109
|
-
let payload;
|
|
110
|
-
try {
|
|
111
|
-
if (status === 204) {
|
|
112
|
-
payload = void 0;
|
|
113
|
-
} else {
|
|
114
|
-
const text = await response.text();
|
|
115
|
-
const parsed = text ? JSON.parse(text) : void 0;
|
|
116
|
-
payload = decode ? decode(parsed) : parsed;
|
|
117
|
-
}
|
|
118
|
-
} catch {
|
|
119
|
-
return fail({ outcome: "invalid_response", status, code: "", message: "", requestId });
|
|
120
|
-
}
|
|
121
|
-
outcome = "success";
|
|
122
|
-
return { payload, status, requestId };
|
|
123
|
-
} finally {
|
|
124
|
-
if (observe) {
|
|
125
|
-
try {
|
|
126
|
-
observe({ method, outcome, status, requestId, durationMs: Math.max(0, Date.now() - startedAt), attempts });
|
|
127
|
-
} catch {
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
// src/service-accounts.ts
|
|
134
|
-
var SERVICE_ACCOUNTS_VIEW_PERMISSION = "platform.service_accounts.view";
|
|
135
|
-
var SERVICE_ACCOUNTS_MANAGE_PERMISSION = "platform.service_accounts.manage";
|
|
136
|
-
var ServiceAccountAPIError = class extends Error {
|
|
137
|
-
constructor(message, status, code, requestId) {
|
|
138
|
-
super(message);
|
|
139
|
-
this.status = status;
|
|
140
|
-
this.code = code;
|
|
141
|
-
this.requestId = requestId;
|
|
142
|
-
this.name = "ServiceAccountAPIError";
|
|
143
|
-
}
|
|
144
|
-
status;
|
|
145
|
-
code;
|
|
146
|
-
requestId;
|
|
147
|
-
};
|
|
148
|
-
function isServiceAccountAPIError(error) {
|
|
149
|
-
return error instanceof ServiceAccountAPIError || typeof error === "object" && error !== null && error.name === "ServiceAccountAPIError" && typeof error.status === "number" && typeof error.code === "string" && typeof error.requestId === "string";
|
|
150
|
-
}
|
|
151
|
-
var basePath = "/api/v1/platform/identity/service-accounts";
|
|
152
|
-
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;
|
|
153
|
-
var credentialIDPattern = /^[0-9a-f]{32}$/;
|
|
154
|
-
var timestampPattern = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;
|
|
155
|
-
var secretPattern = /^mml_sa_([0-9a-f]{32})_([0-9a-f]{64})$/;
|
|
156
|
-
var configurationError = (message) => new Error(message);
|
|
157
|
-
function invalidResponse() {
|
|
158
|
-
throw new Error("invalid Service Account response");
|
|
159
|
-
}
|
|
160
|
-
function objectValue(value) {
|
|
161
|
-
if (typeof value !== "object" || value === null || Array.isArray(value)) invalidResponse();
|
|
162
|
-
return value;
|
|
163
|
-
}
|
|
164
|
-
function responseString(value, options = {}) {
|
|
165
|
-
if (value === void 0 && options.optional) return void 0;
|
|
166
|
-
if (typeof value !== "string" || value.length === 0) invalidResponse();
|
|
167
|
-
if (options.pattern && !options.pattern.test(value)) invalidResponse();
|
|
168
|
-
if (options.timestamp && (!timestampPattern.test(value) || !Number.isFinite(Date.parse(value)))) invalidResponse();
|
|
169
|
-
return value;
|
|
170
|
-
}
|
|
171
|
-
function responseStrings(value) {
|
|
172
|
-
if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string" || entry.length === 0)) {
|
|
173
|
-
invalidResponse();
|
|
174
|
-
}
|
|
175
|
-
return [...value];
|
|
176
|
-
}
|
|
177
|
-
function positiveIntegerResponse(value) {
|
|
178
|
-
if (!Number.isSafeInteger(value) || Number(value) < 1) invalidResponse();
|
|
179
|
-
return Number(value);
|
|
180
|
-
}
|
|
181
|
-
function parseServiceAccount(value) {
|
|
182
|
-
const account = objectValue(value);
|
|
183
|
-
if (typeof account.enabled !== "boolean") invalidResponse();
|
|
184
|
-
return {
|
|
185
|
-
id: responseString(account.id, { pattern: uuidPattern }),
|
|
186
|
-
name: responseString(account.name),
|
|
187
|
-
purpose: responseString(account.purpose),
|
|
188
|
-
owner_user_id: responseString(account.owner_user_id),
|
|
189
|
-
enabled: account.enabled,
|
|
190
|
-
version: positiveIntegerResponse(account.version),
|
|
191
|
-
created_by: responseString(account.created_by),
|
|
192
|
-
updated_by: responseString(account.updated_by),
|
|
193
|
-
created_at: responseString(account.created_at, { timestamp: true }),
|
|
194
|
-
updated_at: responseString(account.updated_at, { timestamp: true })
|
|
195
|
-
};
|
|
196
|
-
}
|
|
197
|
-
function parseServiceAccountEnvelope(value) {
|
|
198
|
-
return { service_account: parseServiceAccount(objectValue(value).service_account) };
|
|
199
|
-
}
|
|
200
|
-
function parsePage(value, parseItem) {
|
|
201
|
-
const page = objectValue(value);
|
|
202
|
-
if (!Array.isArray(page.items) || typeof page.has_more !== "boolean") invalidResponse();
|
|
203
|
-
const nextCursor = responseString(page.next_cursor, { optional: true });
|
|
204
|
-
if (Boolean(nextCursor) !== page.has_more) invalidResponse();
|
|
205
|
-
return { items: page.items.map(parseItem), next_cursor: nextCursor, has_more: page.has_more };
|
|
206
|
-
}
|
|
207
|
-
function parseGrant(value) {
|
|
208
|
-
const grant = objectValue(value);
|
|
209
|
-
return {
|
|
210
|
-
grant_key: responseString(grant.grant_key),
|
|
211
|
-
scope_type: responseString(grant.scope_type),
|
|
212
|
-
scope_id: responseString(grant.scope_id),
|
|
213
|
-
id: responseString(grant.id, { optional: true }),
|
|
214
|
-
subject_id: responseString(grant.subject_id, { optional: true }),
|
|
215
|
-
subject_type: responseString(grant.subject_type, { optional: true }),
|
|
216
|
-
granted_by: responseString(grant.granted_by, { optional: true }),
|
|
217
|
-
created_at: responseString(grant.created_at, { optional: true, timestamp: true })
|
|
218
|
-
};
|
|
219
|
-
}
|
|
220
|
-
function parseCredential(value) {
|
|
221
|
-
const credential = objectValue(value);
|
|
222
|
-
const audience = responseString(credential.audience);
|
|
223
|
-
if (audience !== "platform" && !audience.startsWith("dash:")) invalidResponse();
|
|
224
|
-
return {
|
|
225
|
-
id: responseString(credential.id, { pattern: credentialIDPattern }),
|
|
226
|
-
service_account_id: responseString(credential.service_account_id, { pattern: uuidPattern }),
|
|
227
|
-
name: responseString(credential.name),
|
|
228
|
-
audience,
|
|
229
|
-
permissions: responseStrings(credential.permissions),
|
|
230
|
-
operation_ids: responseStrings(credential.operation_ids),
|
|
231
|
-
dash_ids: responseStrings(credential.dash_ids),
|
|
232
|
-
max_output_bytes: positiveIntegerResponse(credential.max_output_bytes),
|
|
233
|
-
created_by: responseString(credential.created_by),
|
|
234
|
-
created_at: responseString(credential.created_at, { timestamp: true }),
|
|
235
|
-
expires_at: responseString(credential.expires_at, { timestamp: true }),
|
|
236
|
-
last_used_at: responseString(credential.last_used_at, { optional: true, timestamp: true }),
|
|
237
|
-
revoked_at: responseString(credential.revoked_at, { optional: true, timestamp: true })
|
|
238
|
-
};
|
|
239
|
-
}
|
|
240
|
-
function parseMintedCredential(value) {
|
|
241
|
-
const minted = objectValue(value);
|
|
242
|
-
const credential = parseCredential(minted.credential);
|
|
243
|
-
const secret = responseString(minted.secret);
|
|
244
|
-
const match = secret.match(secretPattern);
|
|
245
|
-
if (!match || match[1] !== credential.id) invalidResponse();
|
|
246
|
-
return { credential, secret };
|
|
247
|
-
}
|
|
248
|
-
function canonicalID(value, label, pattern) {
|
|
249
|
-
const id = requiredString(value, label, configurationError);
|
|
250
|
-
if (!pattern.test(id)) throw configurationError(`${label} is invalid`);
|
|
251
|
-
return id;
|
|
252
|
-
}
|
|
253
|
-
function version(value) {
|
|
254
|
-
if (!Number.isSafeInteger(value) || value < 1) throw configurationError("expected_version must be a positive integer");
|
|
255
|
-
return value;
|
|
256
|
-
}
|
|
257
|
-
function reason(value) {
|
|
258
|
-
const normalized = requiredString(value, "reason", configurationError);
|
|
259
|
-
if (normalized.length > 500) throw configurationError("reason must be 500 characters or fewer");
|
|
260
|
-
return normalized;
|
|
261
|
-
}
|
|
262
|
-
function accountFields(input) {
|
|
263
|
-
const name = requiredString(input.name, "name", configurationError);
|
|
264
|
-
const purpose = requiredString(input.purpose, "purpose", configurationError);
|
|
265
|
-
const ownerUserID = requiredString(input.owner_user_id, "owner_user_id", configurationError);
|
|
266
|
-
if (name.length > 64) throw configurationError("name must be 64 characters or fewer");
|
|
267
|
-
if (purpose.length > 500) throw configurationError("purpose must be 500 characters or fewer");
|
|
268
|
-
return { name, purpose, owner_user_id: ownerUserID, reason: reason(input.reason) };
|
|
269
|
-
}
|
|
270
|
-
function listQuery(params) {
|
|
271
|
-
const query = new URLSearchParams();
|
|
272
|
-
const cursor = params.cursor?.trim();
|
|
273
|
-
if (cursor) query.set("cursor", cursor);
|
|
274
|
-
if (params.limit !== void 0) {
|
|
275
|
-
const limit = positiveNumber(params.limit, "limit", configurationError);
|
|
276
|
-
if (!Number.isSafeInteger(limit) || limit > 100) throw configurationError("limit must be an integer from 1 to 100");
|
|
277
|
-
query.set("limit", String(limit));
|
|
278
|
-
}
|
|
279
|
-
return query.size ? `?${query}` : "";
|
|
280
|
-
}
|
|
281
|
-
function grantInput(value) {
|
|
282
|
-
const grantKey = requiredString(value.grant_key, "grant_key", configurationError);
|
|
283
|
-
if (value.scope_type !== "platform" && value.scope_type !== "dash_id") {
|
|
284
|
-
throw configurationError("scope_type must be platform or dash_id");
|
|
285
|
-
}
|
|
286
|
-
const scopeID = requiredString(value.scope_id, "scope_id", configurationError);
|
|
287
|
-
if (value.scope_type === "platform" && scopeID !== "*") {
|
|
288
|
-
throw configurationError('platform grants must use scope_id "*"');
|
|
289
|
-
}
|
|
290
|
-
if (value.scope_type === "dash_id" && scopeID === "*") {
|
|
291
|
-
throw configurationError("service-account Dash grants must name one Dash");
|
|
292
|
-
}
|
|
293
|
-
return { grant_key: grantKey, scope_type: value.scope_type, scope_id: scopeID };
|
|
294
|
-
}
|
|
295
|
-
function mintInput(value) {
|
|
296
|
-
const name = requiredString(value.name, "name", configurationError);
|
|
297
|
-
if (name.length > 64) throw configurationError("name must be 64 characters or fewer");
|
|
298
|
-
const audience = requiredString(value.audience, "audience", configurationError);
|
|
299
|
-
if (audience !== "platform" && !audience.startsWith("dash:")) {
|
|
300
|
-
throw configurationError("audience must be platform or dash:<dash_id>");
|
|
301
|
-
}
|
|
302
|
-
if (value.template !== "read_only" && value.template !== "full" && value.template !== "custom") {
|
|
303
|
-
throw configurationError("template must be read_only, full or custom");
|
|
304
|
-
}
|
|
305
|
-
const permissions = [...new Set((value.permissions ?? []).map((item) => requiredString(item, "permission", configurationError)))];
|
|
306
|
-
if (value.template === "custom" && (permissions.length < 1 || permissions.length > 64)) {
|
|
307
|
-
throw configurationError("a custom template must name 1 to 64 permissions");
|
|
308
|
-
}
|
|
309
|
-
const dashIDs = [...new Set(value.dash_ids.map((item) => requiredString(item, "dash_id", configurationError)))];
|
|
310
|
-
if (dashIDs.length > 32 || dashIDs.includes("*")) throw configurationError("dash_ids must name at most 32 explicit Dashes");
|
|
311
|
-
if (audience.startsWith("dash:") && (dashIDs.length !== 1 || dashIDs[0] !== audience.slice(5))) {
|
|
312
|
-
throw configurationError("a Dash audience requires exactly its route Dash in dash_ids");
|
|
313
|
-
}
|
|
314
|
-
if (!Number.isSafeInteger(value.expires_in_days) || value.expires_in_days < 1 || value.expires_in_days > 30) {
|
|
315
|
-
throw configurationError("expires_in_days must be an integer from 1 to 30");
|
|
316
|
-
}
|
|
317
|
-
if (value.max_output_bytes !== void 0 && (!Number.isSafeInteger(value.max_output_bytes) || value.max_output_bytes < 1 || value.max_output_bytes > 1048576)) {
|
|
318
|
-
throw configurationError("max_output_bytes must be an integer from 1 to 1048576");
|
|
319
|
-
}
|
|
320
|
-
return {
|
|
321
|
-
name,
|
|
322
|
-
audience,
|
|
323
|
-
template: value.template,
|
|
324
|
-
...value.template === "custom" ? { permissions } : {},
|
|
325
|
-
dash_ids: dashIDs,
|
|
326
|
-
expires_in_days: value.expires_in_days,
|
|
327
|
-
expected_version: version(value.expected_version),
|
|
328
|
-
reason: reason(value.reason),
|
|
329
|
-
...value.max_output_bytes === void 0 ? {} : { max_output_bytes: value.max_output_bytes }
|
|
330
|
-
};
|
|
331
|
-
}
|
|
332
|
-
function createServiceAccountClient(options) {
|
|
333
|
-
const baseUrl = requiredString(options.baseUrl, "baseUrl", configurationError).replace(/\/+$/, "");
|
|
334
|
-
const transport = {
|
|
335
|
-
fetch: (input, init) => (options.fetch ?? globalThis.fetch)(input, init),
|
|
336
|
-
timeoutMs: positiveNumber(options.timeoutMs ?? 1e4, "timeoutMs", configurationError),
|
|
337
|
-
retry: {
|
|
338
|
-
attempts: nonNegativeInteger(options.retryAttempts ?? 1, "retryAttempts", configurationError),
|
|
339
|
-
maxDelayMs: positiveNumber(options.maxRetryDelayMs ?? 2e3, "maxRetryDelayMs", configurationError),
|
|
340
|
-
idempotentWrites: false
|
|
341
|
-
},
|
|
342
|
-
signal: options.signal
|
|
343
|
-
};
|
|
344
|
-
async function request(operation, path, decode, init = {}) {
|
|
345
|
-
const method = (init.method ?? "GET").toUpperCase();
|
|
346
|
-
const report = options.observe && ((event) => {
|
|
347
|
-
options.observe?.({ operation, ...event });
|
|
348
|
-
});
|
|
349
|
-
let headers;
|
|
350
|
-
try {
|
|
351
|
-
const accessToken = requiredString(await options.getAccessToken() ?? "", "access token", configurationError);
|
|
352
|
-
headers = new Headers(await options.getHeaders?.());
|
|
353
|
-
new Headers(init.headers).forEach((value, key) => headers.set(key, value));
|
|
354
|
-
headers.set("Authorization", `Bearer ${accessToken}`);
|
|
355
|
-
headers.set("Accept", "application/json");
|
|
356
|
-
if (init.body !== void 0) headers.set("Content-Type", "application/json");
|
|
357
|
-
} catch (error) {
|
|
358
|
-
try {
|
|
359
|
-
report?.({ method, outcome: "network_error", status: 0, requestId: "", durationMs: 0, attempts: 0 });
|
|
360
|
-
} catch {
|
|
361
|
-
}
|
|
362
|
-
throw error;
|
|
363
|
-
}
|
|
364
|
-
try {
|
|
365
|
-
const result = await performRequest(
|
|
366
|
-
transport,
|
|
367
|
-
`${baseUrl}${path}`,
|
|
368
|
-
{ ...init, method, headers, cache: "no-store" },
|
|
369
|
-
report,
|
|
370
|
-
decode
|
|
371
|
-
);
|
|
372
|
-
return result.payload;
|
|
373
|
-
} catch (error) {
|
|
374
|
-
if (!isTransportError(error)) throw error;
|
|
375
|
-
const { outcome, status, code, message, requestId } = error.failure;
|
|
376
|
-
switch (outcome) {
|
|
377
|
-
case "timeout":
|
|
378
|
-
throw new ServiceAccountAPIError("Service Account request timed out", 0, "service_account_request_timeout", "");
|
|
379
|
-
case "cancelled":
|
|
380
|
-
throw new ServiceAccountAPIError("Service Account request was cancelled", 0, "service_account_request_cancelled", "");
|
|
381
|
-
case "network_error":
|
|
382
|
-
throw new ServiceAccountAPIError("Service Account service is unavailable", 0, "service_account_service_unavailable", "");
|
|
383
|
-
case "invalid_response":
|
|
384
|
-
throw new ServiceAccountAPIError("Service Account service returned an invalid response", status, "service_account_invalid_response", requestId);
|
|
385
|
-
case "api_error":
|
|
386
|
-
throw new ServiceAccountAPIError(message || code || "Service Account request failed", status, code, requestId);
|
|
387
|
-
}
|
|
388
|
-
}
|
|
389
|
-
}
|
|
390
|
-
function accountPath(serviceAccountID) {
|
|
391
|
-
return `${basePath}/${canonicalID(serviceAccountID, "serviceAccountId", uuidPattern)}`;
|
|
392
|
-
}
|
|
393
|
-
return {
|
|
394
|
-
list(params = {}) {
|
|
395
|
-
return request(
|
|
396
|
-
"platform.identity.service_accounts.list",
|
|
397
|
-
`${basePath}${listQuery(params)}`,
|
|
398
|
-
(payload) => parsePage(payload, parseServiceAccount)
|
|
399
|
-
);
|
|
400
|
-
},
|
|
401
|
-
get(serviceAccountID) {
|
|
402
|
-
return request(
|
|
403
|
-
"platform.identity.service_accounts.get",
|
|
404
|
-
accountPath(serviceAccountID),
|
|
405
|
-
parseServiceAccountEnvelope
|
|
406
|
-
);
|
|
407
|
-
},
|
|
408
|
-
create(input) {
|
|
409
|
-
return request(
|
|
410
|
-
"platform.identity.service_accounts.create",
|
|
411
|
-
basePath,
|
|
412
|
-
parseServiceAccountEnvelope,
|
|
413
|
-
{ method: "POST", body: JSON.stringify(accountFields(input)) }
|
|
414
|
-
);
|
|
415
|
-
},
|
|
416
|
-
update(serviceAccountID, input) {
|
|
417
|
-
const fields = accountFields(input);
|
|
418
|
-
return request(
|
|
419
|
-
"platform.identity.service_accounts.update",
|
|
420
|
-
accountPath(serviceAccountID),
|
|
421
|
-
parseServiceAccountEnvelope,
|
|
422
|
-
{
|
|
423
|
-
method: "PUT",
|
|
424
|
-
body: JSON.stringify({ ...fields, enabled: input.enabled, expected_version: version(input.expected_version) })
|
|
425
|
-
}
|
|
426
|
-
);
|
|
427
|
-
},
|
|
428
|
-
listGrants(serviceAccountID) {
|
|
429
|
-
return request(
|
|
430
|
-
"platform.identity.service_accounts.grants.list",
|
|
431
|
-
`${accountPath(serviceAccountID)}/grants`,
|
|
432
|
-
(payload) => {
|
|
433
|
-
const page = objectValue(payload);
|
|
434
|
-
if (!Array.isArray(page.items)) invalidResponse();
|
|
435
|
-
return { items: page.items.map(parseGrant) };
|
|
436
|
-
}
|
|
437
|
-
);
|
|
438
|
-
},
|
|
439
|
-
replaceGrants(serviceAccountID, input) {
|
|
440
|
-
if (!Array.isArray(input.grants) || input.grants.length > 32) {
|
|
441
|
-
throw configurationError("grants must contain at most 32 entries");
|
|
442
|
-
}
|
|
443
|
-
return request(
|
|
444
|
-
"platform.identity.service_accounts.grants.replace",
|
|
445
|
-
`${accountPath(serviceAccountID)}/grants`,
|
|
446
|
-
parseServiceAccountEnvelope,
|
|
447
|
-
{
|
|
448
|
-
method: "PUT",
|
|
449
|
-
body: JSON.stringify({
|
|
450
|
-
grants: input.grants.map(grantInput),
|
|
451
|
-
expected_version: version(input.expected_version),
|
|
452
|
-
reason: reason(input.reason)
|
|
453
|
-
})
|
|
454
|
-
}
|
|
455
|
-
);
|
|
456
|
-
},
|
|
457
|
-
listCredentials(serviceAccountID, params = {}) {
|
|
458
|
-
return request(
|
|
459
|
-
"platform.identity.service_accounts.credentials.list",
|
|
460
|
-
`${accountPath(serviceAccountID)}/credentials${listQuery(params)}`,
|
|
461
|
-
(payload) => parsePage(payload, parseCredential)
|
|
462
|
-
);
|
|
463
|
-
},
|
|
464
|
-
mintCredential(serviceAccountID, input) {
|
|
465
|
-
return request(
|
|
466
|
-
"platform.identity.service_accounts.credentials.mint",
|
|
467
|
-
`${accountPath(serviceAccountID)}/credentials`,
|
|
468
|
-
parseMintedCredential,
|
|
469
|
-
{ method: "POST", body: JSON.stringify(mintInput(input)) }
|
|
470
|
-
);
|
|
471
|
-
},
|
|
472
|
-
revokeCredential(serviceAccountID, credentialID, input) {
|
|
473
|
-
return request(
|
|
474
|
-
"platform.identity.service_accounts.credentials.revoke",
|
|
475
|
-
`${accountPath(serviceAccountID)}/credentials/${canonicalID(credentialID, "credentialId", credentialIDPattern)}`,
|
|
476
|
-
parseServiceAccountEnvelope,
|
|
477
|
-
{
|
|
478
|
-
method: "DELETE",
|
|
479
|
-
body: JSON.stringify({ expected_version: version(input.expected_version), reason: reason(input.reason) })
|
|
480
|
-
}
|
|
481
|
-
);
|
|
482
|
-
}
|
|
483
|
-
};
|
|
484
|
-
}
|
|
485
|
-
|
|
486
|
-
export { SERVICE_ACCOUNTS_MANAGE_PERMISSION, SERVICE_ACCOUNTS_VIEW_PERMISSION, ServiceAccountAPIError, createServiceAccountClient, isServiceAccountAPIError };
|