@antasphere/chassis-contract 0.0.0-stage → 1.0.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/LICENSE +82 -0
- package/dist/define.d.ts +177 -0
- package/dist/define.d.ts.map +1 -0
- package/dist/define.js +35 -0
- package/dist/define.js.map +1 -0
- package/dist/entitlements.d.ts +486 -0
- package/dist/entitlements.d.ts.map +1 -0
- package/dist/entitlements.js +344 -0
- package/dist/entitlements.js.map +1 -0
- package/dist/identity.d.ts +56 -0
- package/dist/identity.d.ts.map +1 -0
- package/dist/identity.js +2 -0
- package/dist/identity.js.map +1 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +29 -0
- package/dist/index.js.map +1 -0
- package/dist/routes/index.d.ts +5403 -0
- package/dist/routes/index.d.ts.map +1 -0
- package/dist/routes/index.js +940 -0
- package/dist/routes/index.js.map +1 -0
- package/dist/schemas/api-keys.d.ts +54 -0
- package/dist/schemas/api-keys.d.ts.map +1 -0
- package/dist/schemas/api-keys.js +48 -0
- package/dist/schemas/api-keys.js.map +1 -0
- package/dist/schemas/audit.d.ts +74 -0
- package/dist/schemas/audit.d.ts.map +1 -0
- package/dist/schemas/audit.js +65 -0
- package/dist/schemas/audit.js.map +1 -0
- package/dist/schemas/break-glass.d.ts +42 -0
- package/dist/schemas/break-glass.d.ts.map +1 -0
- package/dist/schemas/break-glass.js +38 -0
- package/dist/schemas/break-glass.js.map +1 -0
- package/dist/schemas/cli-auth.d.ts +59 -0
- package/dist/schemas/cli-auth.d.ts.map +1 -0
- package/dist/schemas/cli-auth.js +68 -0
- package/dist/schemas/cli-auth.js.map +1 -0
- package/dist/schemas/common.d.ts +96 -0
- package/dist/schemas/common.d.ts.map +1 -0
- package/dist/schemas/common.js +205 -0
- package/dist/schemas/common.js.map +1 -0
- package/dist/schemas/demo-passes.d.ts +90 -0
- package/dist/schemas/demo-passes.d.ts.map +1 -0
- package/dist/schemas/demo-passes.js +60 -0
- package/dist/schemas/demo-passes.js.map +1 -0
- package/dist/schemas/files.d.ts +39 -0
- package/dist/schemas/files.d.ts.map +1 -0
- package/dist/schemas/files.js +26 -0
- package/dist/schemas/files.js.map +1 -0
- package/dist/schemas/instance.d.ts +58 -0
- package/dist/schemas/instance.d.ts.map +1 -0
- package/dist/schemas/instance.js +70 -0
- package/dist/schemas/instance.js.map +1 -0
- package/dist/schemas/invitations.d.ts +100 -0
- package/dist/schemas/invitations.d.ts.map +1 -0
- package/dist/schemas/invitations.js +55 -0
- package/dist/schemas/invitations.js.map +1 -0
- package/dist/schemas/me.d.ts +81 -0
- package/dist/schemas/me.d.ts.map +1 -0
- package/dist/schemas/me.js +178 -0
- package/dist/schemas/me.js.map +1 -0
- package/dist/schemas/members.d.ts +60 -0
- package/dist/schemas/members.d.ts.map +1 -0
- package/dist/schemas/members.js +43 -0
- package/dist/schemas/members.js.map +1 -0
- package/dist/schemas/projects.d.ts +232 -0
- package/dist/schemas/projects.d.ts.map +1 -0
- package/dist/schemas/projects.js +140 -0
- package/dist/schemas/projects.js.map +1 -0
- package/dist/schemas/scope.d.ts +14 -0
- package/dist/schemas/scope.d.ts.map +1 -0
- package/dist/schemas/scope.js +5 -0
- package/dist/schemas/scope.js.map +1 -0
- package/dist/schemas/setup.d.ts +28 -0
- package/dist/schemas/setup.d.ts.map +1 -0
- package/dist/schemas/setup.js +28 -0
- package/dist/schemas/setup.js.map +1 -0
- package/dist/schemas/sso-connect.d.ts +30 -0
- package/dist/schemas/sso-connect.d.ts.map +1 -0
- package/dist/schemas/sso-connect.js +38 -0
- package/dist/schemas/sso-connect.js.map +1 -0
- package/dist/schemas/sso-logout.d.ts +17 -0
- package/dist/schemas/sso-logout.d.ts.map +1 -0
- package/dist/schemas/sso-logout.js +16 -0
- package/dist/schemas/sso-logout.js.map +1 -0
- package/dist/schemas/teams.d.ts +100 -0
- package/dist/schemas/teams.d.ts.map +1 -0
- package/dist/schemas/teams.js +84 -0
- package/dist/schemas/teams.js.map +1 -0
- package/dist/schemas/workspaces.d.ts +99 -0
- package/dist/schemas/workspaces.d.ts.map +1 -0
- package/dist/schemas/workspaces.js +96 -0
- package/dist/schemas/workspaces.js.map +1 -0
- package/dist/seams.d.ts +185 -0
- package/dist/seams.d.ts.map +1 -0
- package/dist/seams.js +37 -0
- package/dist/seams.js.map +1 -0
- package/dist/wire.d.ts +101 -0
- package/dist/wire.d.ts.map +1 -0
- package/dist/wire.js +161 -0
- package/dist/wire.js.map +1 -0
- package/package.json +41 -3
- package/src/define.ts +64 -0
- package/src/entitlements.ts +527 -0
- package/src/identity.ts +49 -0
- package/src/index.ts +38 -0
- package/src/routes/index.ts +1146 -0
- package/src/schemas/api-keys.ts +53 -0
- package/src/schemas/audit.ts +74 -0
- package/src/schemas/break-glass.ts +46 -0
- package/src/schemas/cli-auth.ts +78 -0
- package/src/schemas/common.ts +206 -0
- package/src/schemas/demo-passes.ts +73 -0
- package/src/schemas/files.ts +30 -0
- package/src/schemas/instance.ts +71 -0
- package/src/schemas/invitations.ts +66 -0
- package/src/schemas/me.ts +184 -0
- package/src/schemas/members.ts +53 -0
- package/src/schemas/projects.ts +174 -0
- package/src/schemas/scope.ts +18 -0
- package/src/schemas/setup.ts +31 -0
- package/src/schemas/sso-connect.ts +40 -0
- package/src/schemas/sso-logout.ts +17 -0
- package/src/schemas/teams.ts +101 -0
- package/src/schemas/workspaces.ts +109 -0
- package/src/seams.ts +202 -0
- package/src/wire.ts +246 -0
- package/test/define.test.ts +59 -0
- package/test/hub-wire.test.ts +114 -0
- package/README.md +0 -3
|
@@ -0,0 +1,527 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import type { HeaderReader, Principal } from './seams.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The billing rail's declaration layer (the pay-per-use billing rail spec,
|
|
6
|
+
* §7 and §8b): a route says ONCE, next to its contract, what it meters, which
|
|
7
|
+
* limit it checks and which feature it needs. One chassis middleware reads
|
|
8
|
+
* the declaration and enforces it for every client of `/api/v1` at once (the
|
|
9
|
+
* dashboard, the CLI and the MCP tools are all HTTP clients of it), and a
|
|
10
|
+
* handler never checks or emits by hand.
|
|
11
|
+
*
|
|
12
|
+
* Client-safe on purpose: no Hono here. A route is referenced by its
|
|
13
|
+
* `{ method, path }` as the OpenAPI helper spells it (`{id}` params), so the
|
|
14
|
+
* tool's contract builds the registry from its route objects and the SDK can
|
|
15
|
+
* read the same declarations without pulling the server.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The plan tiers, a CLOSED enum the hub owns and this contract mirrors so a
|
|
20
|
+
* tool cannot invent one (§8b). `free` is the default with no subscription;
|
|
21
|
+
* `pro` is the paid plan. "Enterprise" is not a tier but a per-account
|
|
22
|
+
* override the hub serves.
|
|
23
|
+
*/
|
|
24
|
+
export const ENTITLEMENT_TIERS = ['free', 'pro'] as const;
|
|
25
|
+
export type EntitlementTier = (typeof ENTITLEMENT_TIERS)[number];
|
|
26
|
+
export const entitlementTierSchema = z.enum(ENTITLEMENT_TIERS);
|
|
27
|
+
/** The hub's name for the same closed enum (`BILLING_PLANS` in `@antasphere/contract`). */
|
|
28
|
+
export const BILLING_PLANS = ENTITLEMENT_TIERS;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The one scope of the tool → hub machine channel (§6): a `client_credentials`
|
|
32
|
+
* token on the registry client, reaching `/usage/*` and nothing else.
|
|
33
|
+
*/
|
|
34
|
+
export const USAGE_WRITE_SCOPE = 'usage:write';
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* The error codes the three tool routes of the hub (`POST /usage/events`,
|
|
38
|
+
* `GET /usage/entitlements`, `POST /usage/check`) answer with, and the status
|
|
39
|
+
* each rides on: the hub's `USAGE_ROUTE_ERRORS` (PRDCT-2677).
|
|
40
|
+
* `tool_credential_required`: the caller is not a registry tool's machine
|
|
41
|
+
* credential. `unknown_account`: no organization holds the `accountRef` (the
|
|
42
|
+
* check and the entitlements read; the ingest answers it per event instead).
|
|
43
|
+
* `validation_error`: the body or the query does not parse. The chassis maps
|
|
44
|
+
* the check's two (`check.ts`): a 404 `unknown_account` and a 400 are the
|
|
45
|
+
* hub's judgement, allowed and logged, never an outage.
|
|
46
|
+
*/
|
|
47
|
+
export const USAGE_ROUTE_ERRORS = {
|
|
48
|
+
tool_credential_required: 401,
|
|
49
|
+
unknown_account: 404,
|
|
50
|
+
validation_error: 400
|
|
51
|
+
} as const;
|
|
52
|
+
export type UsageRouteError = keyof typeof USAGE_ROUTE_ERRORS;
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* The wire shape of one usage event as the hub ingests it: the hub's
|
|
56
|
+
* `usageEventSchema` (`packages/contract/src/schemas/billing.ts` of the hub,
|
|
57
|
+
* PRDCT-2625), copied here and checked against the hub's wire snapshot
|
|
58
|
+
* (`wire.ts`, `pnpm --filter @antasphere/chassis-contract wire:check`, the
|
|
59
|
+
* `hub-wire` CI job; PRDCT-2677), so the fake hub of the test kit refuses
|
|
60
|
+
* exactly what the real hub refuses (PRDCT-2629). `userId` is the HUB user
|
|
61
|
+
* (the SSO `sub`), never the tool's local id, and null when the actor is a
|
|
62
|
+
* resource owner the tool could not name; `accountRef` is the hub
|
|
63
|
+
* organization id (a uuid) the tool carries as its workspace's central
|
|
64
|
+
* account id. `toolSlug` is accepted by the hub only when it equals the
|
|
65
|
+
* calling token's registry slug — the chassis NEVER sends it: the token is
|
|
66
|
+
* the only authority on the tool's name, the body never names the tool
|
|
67
|
+
* (PRDCT-2629; `UsageEvent` in seams.ts has no such field).
|
|
68
|
+
*/
|
|
69
|
+
export const usageEventSchema = z
|
|
70
|
+
.object({
|
|
71
|
+
id: z.string().regex(/^[0-9A-HJKMNP-TV-Z]{26}$/, 'a ULID'),
|
|
72
|
+
actionKey: z.string().min(1).max(120).optional(),
|
|
73
|
+
meter: z.string().min(1).max(120).optional(),
|
|
74
|
+
quantity: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
|
|
75
|
+
unit: z.string().min(1).max(40),
|
|
76
|
+
occurredAt: z.iso.datetime({ offset: true }),
|
|
77
|
+
workspaceId: z.string().min(1).max(128),
|
|
78
|
+
accountRef: z.uuid(),
|
|
79
|
+
userId: z.string().min(1).max(128).nullable().optional(),
|
|
80
|
+
via: z.enum(['session', 'api_key', 'oauth']),
|
|
81
|
+
resourceType: z.string().min(1).max(80).nullable().optional(),
|
|
82
|
+
resourceId: z.string().min(1).max(256).nullable().optional(),
|
|
83
|
+
toolSlug: z.string().min(1).max(64).optional(),
|
|
84
|
+
source: z.object({
|
|
85
|
+
instanceId: z.string().min(1).max(128),
|
|
86
|
+
edition: z.string().min(1).max(32),
|
|
87
|
+
version: z.string().min(1).max(64)
|
|
88
|
+
})
|
|
89
|
+
})
|
|
90
|
+
.refine((e) => e.actionKey !== undefined || e.meter !== undefined, {
|
|
91
|
+
message: 'actionKey (or its legacy alias meter) is required',
|
|
92
|
+
path: ['actionKey']
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
/** The batch cap of `POST /usage/events` (the hub's `USAGE_EVENTS_BATCH_MAX`): at most this many events per post. */
|
|
96
|
+
export const USAGE_EVENTS_BATCH_MAX = 500;
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* The body of `POST /usage/events` as the hub parses it (its
|
|
100
|
+
* `usageEventsBatchSchema`): one to `USAGE_EVENTS_BATCH_MAX` elements, each
|
|
101
|
+
* judged on its own against `usageEventSchema` afterwards.
|
|
102
|
+
*/
|
|
103
|
+
export const usageEventsBatchSchema = z.object({
|
|
104
|
+
events: z.array(z.unknown()).min(1).max(USAGE_EVENTS_BATCH_MAX)
|
|
105
|
+
});
|
|
106
|
+
export type UsageEventsBatch = z.infer<typeof usageEventsBatchSchema>;
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Why the hub did not accept an event (its `USAGE_REJECT_REASONS`, a closed
|
|
110
|
+
* list): `unknown_account`, `unknown_user`, `tool_mismatch`, and
|
|
111
|
+
* `invalid_event` (the element does not parse, its `occurredAt` falls outside
|
|
112
|
+
* the window, or its price exceeds `Number.MAX_SAFE_INTEGER`; `details` names
|
|
113
|
+
* the field).
|
|
114
|
+
*/
|
|
115
|
+
export const USAGE_REJECT_REASONS = [
|
|
116
|
+
'unknown_account',
|
|
117
|
+
'unknown_user',
|
|
118
|
+
'tool_mismatch',
|
|
119
|
+
'invalid_event'
|
|
120
|
+
] as const;
|
|
121
|
+
export const usageRejectReasonSchema = z.enum(USAGE_REJECT_REASONS);
|
|
122
|
+
export type UsageRejectReason = z.infer<typeof usageRejectReasonSchema>;
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* One element's answer. Since phase 2 an `accepted` result carries the
|
|
126
|
+
* `credits` the hub debited for it (0 when the action has no price).
|
|
127
|
+
*/
|
|
128
|
+
export const usageEventResultSchema = z.object({
|
|
129
|
+
id: z.string().nullable(),
|
|
130
|
+
status: z.enum(['accepted', 'duplicate', 'rejected']),
|
|
131
|
+
reason: usageRejectReasonSchema.optional(),
|
|
132
|
+
details: z.unknown().optional(),
|
|
133
|
+
credits: z.number().int().optional()
|
|
134
|
+
});
|
|
135
|
+
export type UsageEventResult = z.infer<typeof usageEventResultSchema>;
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* The hub's answer to `POST /usage/events`: one result per element, in the
|
|
139
|
+
* batch's order, and the three counts (always sent).
|
|
140
|
+
*/
|
|
141
|
+
export const usageIngestResultSchema = z.object({
|
|
142
|
+
results: z.array(usageEventResultSchema),
|
|
143
|
+
accepted: z.number().int(),
|
|
144
|
+
duplicate: z.number().int(),
|
|
145
|
+
rejected: z.number().int()
|
|
146
|
+
});
|
|
147
|
+
export type UsageIngestResult = z.infer<typeof usageIngestResultSchema>;
|
|
148
|
+
|
|
149
|
+
// ── The hub's window on an event's date (PRDCT-2630 at the hub, PRDCT-2644 here) ──
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* The window an event's `occurredAt` must fall in, measured against the
|
|
153
|
+
* moment the hub receives it: the hub's `USAGE_EVENT_MAX_PAST_MS` and
|
|
154
|
+
* `USAGE_EVENT_MAX_FUTURE_MS` (`packages/contract/src/schemas/billing.ts`
|
|
155
|
+
* of the hub), same names and values, checked against the hub's wire
|
|
156
|
+
* snapshot (`wire.ts`, `wire:check`, the `hub-wire` CI job; PRDCT-2677). Backward, seven days:
|
|
157
|
+
* the queue's retry budget is about eight and a half hours, so an outage of
|
|
158
|
+
* a night is covered many times over, and a week also covers an operator
|
|
159
|
+
* re-driving held jobs by hand. Forward, five minutes: the skew every JWT
|
|
160
|
+
* verifier already tolerates; anything further is a clock that is wrong.
|
|
161
|
+
* Outside the window the hub answers `rejected(invalid_event)` naming
|
|
162
|
+
* `occurredAt` and never clamps, so the poster refuses BEFORE posting: an
|
|
163
|
+
* event the hub would refuse on its date is held where it was made, never
|
|
164
|
+
* counted as a rejection at the hub (PRDCT-2644).
|
|
165
|
+
*/
|
|
166
|
+
export const USAGE_EVENT_MAX_PAST_MS = 7 * 24 * 60 * 60 * 1000;
|
|
167
|
+
export const USAGE_EVENT_MAX_FUTURE_MS = 5 * 60 * 1000;
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Why an event's `occurredAt` is refused against the receipt time, or null
|
|
171
|
+
* when it falls inside the window (both bounds INCLUSIVE). The hub's
|
|
172
|
+
* `usageEventOccurrenceIssue`, copied (the wire snapshot's occurrence table
|
|
173
|
+
* checks it on the hub's offsets): the one comparison both
|
|
174
|
+
* halves run, the hub at ingest against its own clock, the chassis before
|
|
175
|
+
* posting against its best estimate of the receipt (its own clock), so the
|
|
176
|
+
* two never disagree on the sign or the edge.
|
|
177
|
+
*/
|
|
178
|
+
export function usageEventOccurrenceIssue(
|
|
179
|
+
occurredAt: Date,
|
|
180
|
+
receivedAt: Date
|
|
181
|
+
): { path: 'occurredAt'; message: string } | null {
|
|
182
|
+
const delta = occurredAt.getTime() - receivedAt.getTime();
|
|
183
|
+
if (delta < -USAGE_EVENT_MAX_PAST_MS) {
|
|
184
|
+
return {
|
|
185
|
+
path: 'occurredAt',
|
|
186
|
+
message: `more than ${USAGE_EVENT_MAX_PAST_MS / 86_400_000} days before the hub received the event`
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
if (delta > USAGE_EVENT_MAX_FUTURE_MS) {
|
|
190
|
+
return {
|
|
191
|
+
path: 'occurredAt',
|
|
192
|
+
message: `more than ${USAGE_EVENT_MAX_FUTURE_MS / 60_000} minutes after the hub received the event`
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
return null;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// ── POST /usage/check: the price and the balance before an action (§5, §7 step 3) ──
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* The request of `POST /usage/check` (the hub's `UsageCheckRequest`,
|
|
202
|
+
* PRDCT-2663): the paying account, the action key and the quantity of THIS
|
|
203
|
+
* request. `unit` is accepted and ignored by the hub, which prices by its
|
|
204
|
+
* own row; it is sent so the answer's unit can be compared and a mismatch
|
|
205
|
+
* logged.
|
|
206
|
+
*/
|
|
207
|
+
export const usageCheckRequestSchema = z.object({
|
|
208
|
+
accountRef: z.uuid(),
|
|
209
|
+
actionKey: z.string().min(1).max(120),
|
|
210
|
+
quantity: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
|
|
211
|
+
unit: z.string().min(1).max(40).optional()
|
|
212
|
+
});
|
|
213
|
+
export type UsageCheckRequest = z.infer<typeof usageCheckRequestSchema>;
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* The three reasons a check refuses (`null` when allowed), the hub's
|
|
217
|
+
* `USAGE_CHECK_REASONS`: `account_suspended` (checked first, whatever the
|
|
218
|
+
* price), `unpriceable` (the price of this quantity exceeds
|
|
219
|
+
* `Number.MAX_SAFE_INTEGER`: the hub clamps `credits` to that bound, and the
|
|
220
|
+
* ingest would reject the same event on its `quantity`) and
|
|
221
|
+
* `insufficient_credits` (`balance < credits`). Each is a refusal, never an
|
|
222
|
+
* outage (PRDCT-2677).
|
|
223
|
+
*/
|
|
224
|
+
export const USAGE_CHECK_REASONS = ['insufficient_credits', 'account_suspended', 'unpriceable'] as const;
|
|
225
|
+
export type UsageCheckReason = (typeof USAGE_CHECK_REASONS)[number];
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* The hub's answer to `POST /usage/check` (its `UsageCheck`, PRDCT-2663),
|
|
229
|
+
* checked against the hub's wire snapshot (PRDCT-2677): advisory, no side effect. `credits` is the price of
|
|
230
|
+
* this quantity from the price book row effective now (0 and `priced:
|
|
231
|
+
* false` when the tool has no row for the action: views are never priced,
|
|
232
|
+
* an unknown key is not a refusal); `balance` the account's; `allowed` is
|
|
233
|
+
* `balance >= credits` unless the organization is suspended, which refuses
|
|
234
|
+
* whatever the price. `topUpUrl` is always present: the hub's billing page
|
|
235
|
+
* for that organization, what a `402 entitlement_denied` carries straight
|
|
236
|
+
* off the answer. No lower bound on `quantity` or `credits`, as at the hub: a
|
|
237
|
+
* copy stricter than the hub reads a valid answer as an outage.
|
|
238
|
+
*/
|
|
239
|
+
export const usageCheckSchema = z.object({
|
|
240
|
+
accountRef: z.uuid(),
|
|
241
|
+
actionKey: z.string(),
|
|
242
|
+
quantity: z.number().int(),
|
|
243
|
+
allowed: z.boolean(),
|
|
244
|
+
credits: z.number().int(),
|
|
245
|
+
balance: z.number().int(),
|
|
246
|
+
unit: z.string().nullable(),
|
|
247
|
+
priced: z.boolean(),
|
|
248
|
+
plan: entitlementTierSchema,
|
|
249
|
+
reason: z.enum(USAGE_CHECK_REASONS).nullable(),
|
|
250
|
+
topUpUrl: z.string()
|
|
251
|
+
});
|
|
252
|
+
export type UsageCheck = z.infer<typeof usageCheckSchema>;
|
|
253
|
+
|
|
254
|
+
/** The wire code of a credit refusal (§7 step 4), and its `details`. */
|
|
255
|
+
export const ENTITLEMENT_DENIED = 'entitlement_denied';
|
|
256
|
+
export interface EntitlementDeniedDetails {
|
|
257
|
+
/** The price of this action, in credits. */
|
|
258
|
+
credits: number;
|
|
259
|
+
/** The organization's balance, in credits. */
|
|
260
|
+
balance: number;
|
|
261
|
+
/** The hub's billing page for the organization: where a human adds credits. */
|
|
262
|
+
topUpUrl: string;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* What a declaration's functions see: the request as the chassis reads it.
|
|
267
|
+
* `audit` is present only AFTER the handler ran (the emit), carrying what the
|
|
268
|
+
* handler recorded for its audit row — the place a stored size or a created
|
|
269
|
+
* resource id lives.
|
|
270
|
+
*/
|
|
271
|
+
export interface EntitlementRequest {
|
|
272
|
+
method: string;
|
|
273
|
+
path: string;
|
|
274
|
+
headers: HeaderReader;
|
|
275
|
+
/** Route params by name (`{id}` → its value). */
|
|
276
|
+
params: Record<string, string>;
|
|
277
|
+
principal: Principal | null;
|
|
278
|
+
/**
|
|
279
|
+
* The parsed JSON body of the request, read once and shared with the
|
|
280
|
+
* handler's own validation (the server caches the parse); `undefined`
|
|
281
|
+
* when the request carries none or it does not parse (the route's
|
|
282
|
+
* validator then answers 400 itself). A count limit or a conditional
|
|
283
|
+
* feature reads what the request asks for here (PRDCT-2702): the mint
|
|
284
|
+
* of a share link with a password, the address an invitation names.
|
|
285
|
+
*/
|
|
286
|
+
body: () => Promise<unknown>;
|
|
287
|
+
audit?:
|
|
288
|
+
| { action: string; resourceType: string; resourceId?: string; metadata?: Record<string, unknown> }
|
|
289
|
+
| undefined;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Who pays and who is reported (§8): the organization's account pays, the
|
|
294
|
+
* user is reported. The default actor is the principal; a route on an
|
|
295
|
+
* anonymous surface resolves its resource's owner here instead (share token
|
|
296
|
+
* → deck → owner → the owner's workspace and account) — the viewer is never
|
|
297
|
+
* identified.
|
|
298
|
+
*/
|
|
299
|
+
export interface ActorRef {
|
|
300
|
+
/** The reported user, or null when the actor is a resource owner the tool could not name. */
|
|
301
|
+
userId: string | null;
|
|
302
|
+
workspaceId: string;
|
|
303
|
+
/** The paying account (the workspace's central account id); absent = unmetered (oss, or a cloud-local workspace). */
|
|
304
|
+
accountRef?: string | undefined;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* The actor of a request when it is not the principal: the owner of a
|
|
309
|
+
* resource reached anonymously (a form response through a share link), or
|
|
310
|
+
* the workspace a public door opens (an invitation accepted, a collaborator
|
|
311
|
+
* grant claimed). Resolves null to leave the route to its own handling.
|
|
312
|
+
*/
|
|
313
|
+
export type ActorHook = (ctx: EntitlementRequest) => Promise<ActorRef | null> | ActorRef | null;
|
|
314
|
+
|
|
315
|
+
export interface MeterDeclaration {
|
|
316
|
+
/** The action key, namespaced by the tool's price book (`things.publish`). */
|
|
317
|
+
key: string;
|
|
318
|
+
/** The unit the price is per (`call`, `bytes`, `items`). */
|
|
319
|
+
unit: string;
|
|
320
|
+
/** The quantity of this request; default 1. Called before the handler (the check) and after it (the emit, with `audit` set). */
|
|
321
|
+
quantity?: (ctx: EntitlementRequest) => number;
|
|
322
|
+
/** The actor when it is not the principal (the owner of a resource reached anonymously). */
|
|
323
|
+
actor?: ActorHook;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
export interface LimitDeclaration {
|
|
327
|
+
/** The limit key (`things.maxBytes`), declared with its per-tier values in the tool's `entitlements` slot. */
|
|
328
|
+
key: string;
|
|
329
|
+
/**
|
|
330
|
+
* The value this request observes, compared against the tier's value; over
|
|
331
|
+
* it is a plan refusal. A SIZE limit reads the declared length
|
|
332
|
+
* (`declaredContentLength`, synchronous: the gate then also demands a
|
|
333
|
+
* Content-Length on a metered account). A COUNT limit (PRDCT-2702) may be
|
|
334
|
+
* asynchronous and read the body and the tool's own tables: it returns the
|
|
335
|
+
* count AFTER this action (the resource's things plus this one), so
|
|
336
|
+
* `observed > max` is the refusal, and `null` when there is nothing to
|
|
337
|
+
* judge (the resource does not resolve, the caller may not see it): the
|
|
338
|
+
* gate then lets the route answer on its own.
|
|
339
|
+
*/
|
|
340
|
+
value: (ctx: EntitlementRequest) => number | null | Promise<number | null>;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* A feature a route needs, with an optional condition on the request
|
|
345
|
+
* (PRDCT-2702): a route that creates a thing needs `things.premium` only
|
|
346
|
+
* when the body asks for the premium option, so a declaration on the route
|
|
347
|
+
* refuses the act and never the route. Absent `when`, the whole route needs
|
|
348
|
+
* the feature.
|
|
349
|
+
*/
|
|
350
|
+
export interface FeatureDeclaration {
|
|
351
|
+
key: string;
|
|
352
|
+
when?: (ctx: EntitlementRequest) => boolean | Promise<boolean>;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
export interface RouteEntitlement {
|
|
356
|
+
meter?: MeterDeclaration | undefined;
|
|
357
|
+
limit?: LimitDeclaration | undefined;
|
|
358
|
+
/** A feature key (`things.premium`), declared with its per-tier switch in the tool's `entitlements` slot, or the key with a condition. */
|
|
359
|
+
feature?: string | FeatureDeclaration | undefined;
|
|
360
|
+
/**
|
|
361
|
+
* The actor of a route that meters nothing but checks a limit or a feature
|
|
362
|
+
* on a PUBLIC door (no principal): the workspace the door opens pays and is
|
|
363
|
+
* judged. A meter's own `actor` serves the same purpose on a metered route;
|
|
364
|
+
* this one covers the limit-only shape. Either makes the route a viewer's
|
|
365
|
+
* surface: every refusal to it is one neutral sentence.
|
|
366
|
+
*/
|
|
367
|
+
actor?: ActorHook | undefined;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/** The key of a route's feature declaration, whichever shape it uses; null when none. */
|
|
371
|
+
export function featureKeyOf(entry: RouteEntitlement): string | null {
|
|
372
|
+
if (!entry.feature) return null;
|
|
373
|
+
return typeof entry.feature === 'string' ? entry.feature : entry.feature.key;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/** The actor hook of a route, the entry's own or its meter's; null when the principal is the actor. */
|
|
377
|
+
export function actorHookOf(entry: RouteEntitlement): ActorHook | null {
|
|
378
|
+
return entry.actor ?? entry.meter?.actor ?? null;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** A route as the contract spells it: the OpenAPI method and the `{param}` path. */
|
|
382
|
+
export interface RouteRef {
|
|
383
|
+
method: string;
|
|
384
|
+
path: string;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
export interface RouteEntitlementEntry extends RouteEntitlement {
|
|
388
|
+
route: RouteRef;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/** `METHOD /path` — the registry key of a route. */
|
|
392
|
+
export function routeEntitlementKey(route: RouteRef): string {
|
|
393
|
+
return `${route.method.toUpperCase()} ${route.path}`;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
export type RouteEntitlementDeclarations = ReadonlyMap<string, RouteEntitlementEntry>;
|
|
397
|
+
|
|
398
|
+
/**
|
|
399
|
+
* Build the registry from the tool's route objects. One entry per route: a
|
|
400
|
+
* second declaration of the same route throws at module load, so a typo or a
|
|
401
|
+
* copy cannot silently double or replace a price.
|
|
402
|
+
*/
|
|
403
|
+
export function declareRouteEntitlements(
|
|
404
|
+
entries: ReadonlyArray<RouteEntitlementEntry>
|
|
405
|
+
): RouteEntitlementDeclarations {
|
|
406
|
+
const map = new Map<string, RouteEntitlementEntry>();
|
|
407
|
+
for (const entry of entries) {
|
|
408
|
+
const key = routeEntitlementKey(entry.route);
|
|
409
|
+
if (map.has(key)) throw new Error(`route entitlement declared twice: ${key}`);
|
|
410
|
+
if (!entry.meter && !entry.limit && !entry.feature) {
|
|
411
|
+
throw new Error(`route entitlement declares nothing: ${key}`);
|
|
412
|
+
}
|
|
413
|
+
map.set(key, entry);
|
|
414
|
+
}
|
|
415
|
+
return map;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/** The declared body size of a request (its `Content-Length`), 0 when absent or malformed. */
|
|
419
|
+
export function declaredContentLength(ctx: EntitlementRequest): number {
|
|
420
|
+
const n = Number(ctx.headers.get('content-length') ?? '0');
|
|
421
|
+
return Number.isFinite(n) && n > 0 ? n : 0;
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/**
|
|
425
|
+
* The stored size a handler recorded in its audit metadata (`sizeBytes`),
|
|
426
|
+
* falling back to the declared body size before the handler ran. The check
|
|
427
|
+
* sees the declared size, the emit sees the bytes that were actually kept.
|
|
428
|
+
*/
|
|
429
|
+
export function auditedSizeBytes(ctx: EntitlementRequest): number {
|
|
430
|
+
const stored = ctx.audit?.metadata?.sizeBytes;
|
|
431
|
+
if (typeof stored === 'number' && Number.isFinite(stored) && stored >= 0) return stored;
|
|
432
|
+
return declaredContentLength(ctx);
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
// ── The tool's declared defaults, as `GET /instance` shows them ────────────
|
|
436
|
+
|
|
437
|
+
/**
|
|
438
|
+
* A priced action: the default the hub seeds its price book from (§7); the
|
|
439
|
+
* hub's rows win afterwards. `creditsPerUnit` credits buy `per` units of
|
|
440
|
+
* `unit` (`per` defaults to 1): an action metered in bytes and priced per
|
|
441
|
+
* mebibyte declares `{ creditsPerUnit: 5, unit: 'bytes', per: 1048576 }`,
|
|
442
|
+
* so the meter stays exact, the price reads as the seed table says it, and
|
|
443
|
+
* the two agree by construction (PRDCT-2627: the boot refuses a route whose
|
|
444
|
+
* meter unit differs from its action's). The hub prices an event as
|
|
445
|
+
* `creditsPerUnit × quantity / per`; rounding a fraction of a credit is the
|
|
446
|
+
* hub's rule, not the tool's.
|
|
447
|
+
*/
|
|
448
|
+
export const entitlementActionSchema = z.object({
|
|
449
|
+
key: z.string().min(1),
|
|
450
|
+
creditsPerUnit: z.number().int().min(0),
|
|
451
|
+
unit: z.string().min(1),
|
|
452
|
+
/** How many units one `creditsPerUnit` buys; 1 when absent. */
|
|
453
|
+
per: z.number().int().min(1).optional(),
|
|
454
|
+
label: z.string().min(1)
|
|
455
|
+
});
|
|
456
|
+
export type EntitlementAction = z.infer<typeof entitlementActionSchema>;
|
|
457
|
+
|
|
458
|
+
/**
|
|
459
|
+
* The credits an action declares for a quantity: `creditsPerUnit × quantity
|
|
460
|
+
* / per`, exact (a fraction is the hub's to round). A test pins the seed
|
|
461
|
+
* values with it, so a unit slip (5 per byte where 5 per MB was meant)
|
|
462
|
+
* fails before the price book is seeded from discovery.
|
|
463
|
+
*/
|
|
464
|
+
export function declaredCredits(
|
|
465
|
+
action: Pick<EntitlementAction, 'creditsPerUnit' | 'per'>,
|
|
466
|
+
quantity: number
|
|
467
|
+
): number {
|
|
468
|
+
return (action.creditsPerUnit * quantity) / (action.per ?? 1);
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
/** A limit's value per tier plus the oss value (the operator's own knob); null = unlimited. */
|
|
472
|
+
export const tierLimitSchema = z.object({
|
|
473
|
+
oss: z.number().nullable(),
|
|
474
|
+
free: z.number().nullable(),
|
|
475
|
+
pro: z.number().nullable()
|
|
476
|
+
});
|
|
477
|
+
export type TierLimit = z.infer<typeof tierLimitSchema>;
|
|
478
|
+
|
|
479
|
+
/** A feature's switch per tier (oss has every feature: a self-hosted instance knows no plan). */
|
|
480
|
+
export const tierFeatureSchema = z.object({
|
|
481
|
+
free: z.boolean(),
|
|
482
|
+
pro: z.boolean()
|
|
483
|
+
});
|
|
484
|
+
export type TierFeature = z.infer<typeof tierFeatureSchema>;
|
|
485
|
+
|
|
486
|
+
export const toolEntitlementsSchema = z.object({
|
|
487
|
+
actions: z.array(entitlementActionSchema),
|
|
488
|
+
limits: z.record(z.string(), tierLimitSchema),
|
|
489
|
+
features: z.record(z.string(), tierFeatureSchema)
|
|
490
|
+
});
|
|
491
|
+
export type ToolEntitlements = z.infer<typeof toolEntitlementsSchema>;
|
|
492
|
+
|
|
493
|
+
/**
|
|
494
|
+
* The hub's answer to `GET /usage/entitlements?accountRef=` (§5): the hub's
|
|
495
|
+
* `usageEntitlementsSchema` (PRDCT-2636), checked against the hub's wire
|
|
496
|
+
* snapshot (PRDCT-2677). The account's
|
|
497
|
+
* plan, resolved from the tier's defaults and the account's overrides; in
|
|
498
|
+
* phase 1 `limits` and `features` are empty and the tool's own declared
|
|
499
|
+
* values fill the numbers. A limit's value is a number or a boolean: the
|
|
500
|
+
* hub may switch a numeric limit off or on per account (`true` = unlimited,
|
|
501
|
+
* `false` = nothing allowed; `profiles.ts` resolves it so). Since phase 2
|
|
502
|
+
* (PRDCT-2663) the hub serves its real rows — every limit key it holds for
|
|
503
|
+
* the calling tool and the features on for the account — and `upgradeUrl`,
|
|
504
|
+
* its upgrade page for the organization carrying `org`, `tool` and `plan`;
|
|
505
|
+
* the chassis appends `&key=<key>&requiredPlan=<tier>` at refusal time.
|
|
506
|
+
* Required: every hub since 0.11.0 sends it.
|
|
507
|
+
*/
|
|
508
|
+
export const entitlementProfileSchema = z.object({
|
|
509
|
+
accountRef: z.uuid(),
|
|
510
|
+
plan: entitlementTierSchema,
|
|
511
|
+
/** Until when the plan is paid for (ISO 8601); null on `free` and on a live subscription. */
|
|
512
|
+
planUntil: z.string().nullable(),
|
|
513
|
+
limits: z.record(z.string(), z.union([z.number(), z.boolean()])),
|
|
514
|
+
features: z.array(z.string()),
|
|
515
|
+
upgradeUrl: z.string()
|
|
516
|
+
});
|
|
517
|
+
export type EntitlementProfile = z.infer<typeof entitlementProfileSchema>;
|
|
518
|
+
|
|
519
|
+
/** The wire code of a plan refusal, and its `details` (§7 step 2). */
|
|
520
|
+
export const PLAN_REQUIRED = 'plan_required';
|
|
521
|
+
export interface PlanRequiredDetails {
|
|
522
|
+
key: string;
|
|
523
|
+
plan: EntitlementTier;
|
|
524
|
+
/** The first tier that allows the action, or null when none does. */
|
|
525
|
+
requiredPlan: EntitlementTier | null;
|
|
526
|
+
upgradeUrl: string;
|
|
527
|
+
}
|
package/src/identity.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A tool's IDENTITY: every value that names the tool where a person, an agent
|
|
3
|
+
* or an operator can see it. The chassis packages spell none of them; a tool
|
|
4
|
+
* writes ONE value of this type (in its own contract package, the one package
|
|
5
|
+
* its server, SDK, CLI and dashboard all depend on) and hands it to the three
|
|
6
|
+
* chassis entry points: `defineChassisContract` + `defineChassisRoutes` here,
|
|
7
|
+
* the server's `ToolDefinition.identity`, and the CLI's `defineCli`.
|
|
8
|
+
*
|
|
9
|
+
* Pure data, client-safe. The tool's domain WORDING (a refusal that names its
|
|
10
|
+
* resource) is not identity: it goes to the server's `copy` slot.
|
|
11
|
+
*/
|
|
12
|
+
export interface ToolIdentity<TScope extends string = string> {
|
|
13
|
+
/** Machine name, lower case (`acme`): the CLI's config namespace and its hub connect name. */
|
|
14
|
+
slug: string;
|
|
15
|
+
/** Human name (`Acme`): mails, the no-dashboard page, CLI messages, the name of an instance not set up yet. */
|
|
16
|
+
displayName: string;
|
|
17
|
+
/** API key prefix, without the underscore (`acm` mints `acm_<keyId>_<secret>`). Never change it once keys exist. */
|
|
18
|
+
apiKeyPrefix: string;
|
|
19
|
+
/** The scope vocabulary, by the part each scope plays. `dataExport` is the opt-in full-workspace export. */
|
|
20
|
+
scopes: { read: TScope; write: TScope; dataExport: TScope };
|
|
21
|
+
/** How the OpenAPI document names the CLI key's grant (`things:read+write`). A literal: a contraction, not a join. */
|
|
22
|
+
cliKeyScopesLabel: string;
|
|
23
|
+
/**
|
|
24
|
+
* The tool's cloud home (PRDCT-2947): the instance Antasphere operates
|
|
25
|
+
* (`https://acme.antasphere.com`). The CLI resolves its URL there last
|
|
26
|
+
* (flag → env → profile → this), so `antasphere login` then `acme list`
|
|
27
|
+
* works on a clean machine; the implicit `cloud` profile lives at it. A
|
|
28
|
+
* self-hosted instance is named once, as a profile named for its host.
|
|
29
|
+
*/
|
|
30
|
+
cloud: { url: string };
|
|
31
|
+
cli: {
|
|
32
|
+
/** The binary's name (`acme`). Must equal the `bin` key of the CLI's package.json. */
|
|
33
|
+
bin: string;
|
|
34
|
+
/** Prefix of the CLI's environment variables (`ACME` reads `ACME_URL`, `ACME_API_KEY`, `ACME_WORKSPACE`). */
|
|
35
|
+
envPrefix: string;
|
|
36
|
+
/** A pre-hub config directory still read once for migration (`~/.config/<dir>/config.json`). */
|
|
37
|
+
legacyConfigDir: string;
|
|
38
|
+
};
|
|
39
|
+
mcp: {
|
|
40
|
+
/** `serverInfo.name` of the bundled MCP server. */
|
|
41
|
+
serverName: string;
|
|
42
|
+
/** Prefix of the tool's MCP tool names, underscore included (`acme_`). The tool registers `<prefix>whoami`. */
|
|
43
|
+
toolPrefix: string;
|
|
44
|
+
};
|
|
45
|
+
/** OpenTelemetry `service.name`. */
|
|
46
|
+
otelServiceName: string;
|
|
47
|
+
/** The published container image. Read by nothing at run time: recorded so an instantiate script has one source. */
|
|
48
|
+
imageName: string;
|
|
49
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// Client-safe entry: pure zod schemas + seam types. No Hono anywhere on this
|
|
2
|
+
// path — the dashboard and SDK import from here and must stay server-free.
|
|
3
|
+
//
|
|
4
|
+
// The generic half of the platform contract. Everything is a static export
|
|
5
|
+
// EXCEPT what carries the tool's scope vocabulary: that comes out of
|
|
6
|
+
// `defineChassisContract({ scopes })`, instantiated once by the tool from its
|
|
7
|
+
// identity (`ToolIdentity`, ./identity.ts: the type only, the value is the tool's).
|
|
8
|
+
export * from './schemas/common.js';
|
|
9
|
+
export * from './schemas/scope.js';
|
|
10
|
+
export * from './schemas/instance.js';
|
|
11
|
+
export * from './schemas/setup.js';
|
|
12
|
+
export { onboardingDismissedSchema, type OnboardingDismissed } from './schemas/me.js';
|
|
13
|
+
export * from './schemas/workspaces.js';
|
|
14
|
+
export * from './schemas/members.js';
|
|
15
|
+
export {
|
|
16
|
+
cliAuthRequestSchema,
|
|
17
|
+
cliAuthRequestedSchema,
|
|
18
|
+
cliAuthCompleteSchema,
|
|
19
|
+
cliAuthRevokedSchema,
|
|
20
|
+
type CliAuthRequest,
|
|
21
|
+
type CliAuthRequested,
|
|
22
|
+
type CliAuthComplete,
|
|
23
|
+
type CliAuthRevoked
|
|
24
|
+
} from './schemas/cli-auth.js';
|
|
25
|
+
export * from './schemas/sso-connect.js';
|
|
26
|
+
export * from './schemas/sso-logout.js';
|
|
27
|
+
export * from './schemas/invitations.js';
|
|
28
|
+
export * from './schemas/audit.js';
|
|
29
|
+
export * from './schemas/break-glass.js';
|
|
30
|
+
export * from './schemas/files.js';
|
|
31
|
+
export * from './schemas/projects.js';
|
|
32
|
+
export * from './schemas/teams.js';
|
|
33
|
+
export * from './schemas/demo-passes.js';
|
|
34
|
+
export * from './seams.js';
|
|
35
|
+
export * from './entitlements.js';
|
|
36
|
+
export * from './wire.js';
|
|
37
|
+
export * from './define.js';
|
|
38
|
+
export type { ToolIdentity } from './identity.js';
|