@happyvertical/smrt-support-contract 0.0.0-stage → 0.74.5

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/AGENTS.md ADDED
@@ -0,0 +1,34 @@
1
+ # @happyvertical/smrt-support-contract
2
+
3
+ Public wire contract for HappyVertical Work's signed product support intake
4
+ API: DTOs and limits (`types.ts`), the HMAC signing and verification helper
5
+ (`signing.ts`), the hosted support registry DTOs (`registry.ts`), and a thin
6
+ fetch client (`client.ts`). Work's route handlers import the same types and
7
+ verifier, and `@happyvertical/smrt-product-kit/support` builds on the client,
8
+ so the wire contract has one owner and cannot drift between the two sides.
9
+
10
+ Lifted from `@happyvertical/work-support-contract` 0.3.0
11
+ (happyvertical.com, `packages/work-support-contract`, commit
12
+ `80fb450aca747f10ce98171b5a8758678cc8e2ad`). It is published to the public
13
+ npm registry so Docker builds resolve it without registry credentials; no
14
+ product may vendor a copy.
15
+
16
+ ## Rules
17
+
18
+ - Zero runtime dependencies beyond `node:crypto` and global `fetch`. It is a
19
+ leaf: no runtime dependency on another smrt package (`smrt-core` is a build-time devDependency only, for the shared vite config).
20
+ - Changes are additive. A new field or route is optional on the wire; a
21
+ signature, header name or path change breaks every deployed product.
22
+ - Never put Work internals (tenant ids, profile ids, AI-run data, internal
23
+ events, compensation) into a DTO. Everything here is product-visible.
24
+ - `registry.ts` DTOs never carry a tenant id.
25
+ - Keep behaviour in step with the Work side when `types.ts`, `signing.ts` or
26
+ the paths change; the signing vectors in `signing.test.ts` pin the format.
27
+
28
+ ## Commands
29
+
30
+ ```bash
31
+ pnpm --filter @happyvertical/smrt-support-contract build
32
+ pnpm --filter @happyvertical/smrt-support-contract test
33
+ pnpm --filter @happyvertical/smrt-support-contract typecheck
34
+ ```
package/CLAUDE.md ADDED
@@ -0,0 +1 @@
1
+ @AGENTS.md
package/LICENSE ADDED
@@ -0,0 +1,7 @@
1
+ Copyright <2025> <Happy Vertical Corporation>
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,47 @@
1
- # Temporary Holding Version
1
+ # @happyvertical/smrt-support-contract
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The public wire contract for HappyVertical Work's signed product support
4
+ intake API: request and response types, limits and validators, the HMAC
5
+ request signing and verification helper, and a thin fetch client. Products
6
+ that submit support cases to Work depend on this package (usually through
7
+ [`@happyvertical/smrt-product-kit`](../smrt-product-kit/README.md)) instead of
8
+ vendoring a copy, and it resolves from the public npm registry with no
9
+ credentials, so unauthenticated Docker builds work.
10
+
11
+ Agent/developer guidance: [AGENTS.md](./AGENTS.md).
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ pnpm add @happyvertical/smrt-support-contract
17
+ ```
18
+
19
+ ## Usage
20
+
21
+ ```ts
22
+ import { createSupportClient } from '@happyvertical/smrt-support-contract';
23
+
24
+ const support = createSupportClient({
25
+ baseUrl: process.env.WORK_SUPPORT_URL,
26
+ productKey: process.env.WORK_SUPPORT_PRODUCT_KEY,
27
+ secret: process.env.WORK_SUPPORT_SECRET,
28
+ });
29
+
30
+ await support.submit({
31
+ submissionId: 'case-1',
32
+ subject: 'Cannot sign in',
33
+ description: 'The sign-in button does nothing on the home page.',
34
+ externalUser: { id: 'user-1' },
35
+ });
36
+ ```
37
+
38
+ Signing is exposed separately for servers that verify requests:
39
+ `signSupportRequest(productKey, input)` and `verifySupportSignature(input)`.
40
+ Signatures bind the timestamp, method, path with query and the body, and are
41
+ valid for 300 seconds of clock skew.
42
+
43
+ ## Origin
44
+
45
+ Lifted from `@happyvertical/work-support-contract` 0.3.0
46
+ (`packages/work-support-contract` in happyvertical.com, commit
47
+ `80fb450aca747f10ce98171b5a8758678cc8e2ad`).
@@ -0,0 +1,60 @@
1
+ import { type SupportAdminCaseResponse, type SupportAdminListQuery, type SupportAdminListResponse, type SupportClaimRequest, type SupportClaimResponse, type SupportReplyRequest, type SupportReplyResponse, type SupportSubmissionView, type SupportSubmitRequest, type SupportSubmitResponse, type SupportTranscribeResponse, type SupportUploadResponse, type SupportUserSubmissionsQuery, type SupportUserSubmissionsResponse } from './types.js';
2
+ export declare class SupportApiError extends Error {
3
+ readonly status: number;
4
+ readonly code: string;
5
+ constructor(status: number, code: string);
6
+ }
7
+ export interface SupportClientOptions {
8
+ /** Origin of the Work deployment, e.g. `https://work.happyvertical.com`. */
9
+ baseUrl: string;
10
+ productKey: string;
11
+ secret: string;
12
+ fetch?: typeof fetch;
13
+ now?: () => number;
14
+ }
15
+ export interface SupportClient {
16
+ submit(request: SupportSubmitRequest): Promise<SupportSubmitResponse>;
17
+ /** Submitter read-back: the client-visible timeline for one submission. */
18
+ getSubmission(submissionId: string, options?: {
19
+ externalUserId?: string;
20
+ }): Promise<SupportSubmissionView>;
21
+ /** Post the user's follow-up to their own submission. Idempotent on `messageId`. */
22
+ replyToSubmission(submissionId: string, request: SupportReplyRequest): Promise<SupportReplyResponse>;
23
+ /** The user's own submissions, newest activity first. Scoped to this product. */
24
+ listUserSubmissions(externalUserId: string, query?: SupportUserSubmissionsQuery): Promise<SupportUserSubmissionsResponse>;
25
+ /** Move an anonymous user's submissions to an account. Idempotent. */
26
+ claimUserSubmissions(request: SupportClaimRequest): Promise<SupportClaimResponse>;
27
+ /**
28
+ * Uploads one binary attachment (png, jpeg, webp, webm/wav/ogg/mp4 audio) and
29
+ * returns its id for `attachmentIds`. The HMAC covers the bytes. `contentType`
30
+ * must match what Work sniffs from them (parameters such as `;codecs=opus`
31
+ * are ignored); `sha256` is an optional lowercase-hex integrity check.
32
+ */
33
+ uploadAttachment(bytes: Uint8Array, options: {
34
+ contentType: string;
35
+ sha256?: string;
36
+ }): Promise<SupportUploadResponse>;
37
+ /**
38
+ * Transcribes one short voice clip (at most `SUPPORT_LIMITS.transcribeMaxSeconds`
39
+ * seconds and `transcribeMaxBytes` bytes; same media types and `contentType` rule
40
+ * as `uploadAttachment`). Nothing is stored. Counts against this product's daily
41
+ * transcription budget: a spent budget answers 429.
42
+ */
43
+ transcribe(bytes: Uint8Array, options: {
44
+ contentType: string;
45
+ }): Promise<SupportTranscribeResponse>;
46
+ /**
47
+ * Product-admin tier: the bytes of one attachment on one of this product's
48
+ * cases. Work checks the product and the case binding; the product's own
49
+ * backend must gate which admins may call it.
50
+ */
51
+ downloadAttachment(caseNumber: string, attachmentId: string): Promise<{
52
+ bytes: Uint8Array;
53
+ contentType: string;
54
+ }>;
55
+ /** Product-admin tier. The product's own backend must gate who may call it. */
56
+ listCases(query?: SupportAdminListQuery): Promise<SupportAdminListResponse>;
57
+ getCase(caseNumber: string): Promise<SupportAdminCaseResponse>;
58
+ }
59
+ export declare function createSupportClient(options: SupportClientOptions): SupportClient;
60
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AACA,OAAO,EAKL,KAAK,wBAAwB,EAC7B,KAAK,qBAAqB,EAC1B,KAAK,wBAAwB,EAC7B,KAAK,mBAAm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AAE,UAAU,EACjB,OAAO,EAAE;QAAE,WAAW,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAA;KAAE,GAChD,OAAO,CAAC,qBAAqB,CAAC,CAAC;IAClC;;;;;OAKG;IACH,UAAU,CACR,KAAK,EAAE,UAAU,EACjB,OAAO,EAAE;QAAE,WAAW,EAAE,MAAM,CAAA;KAAE,GAC/B,OAAO,CAAC,yBAAyB,CAAC,CAAC;IACtC;;;;OAIG;IACH,kBAAkB,CAChB,UAAU,EAAE,MAAM,EAClB,YAAY,EAAE,MAAM,GACnB,OAAO,CAAC;QAAE,KAAK,EAAE,UAAU,CAAC;QAAC,WAAW,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACvD,+EAA+E;IAC/E,SAAS,CAAC,KAAK,CAAC,EAAE,qBAAqB,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAAC;IAC5E,OAAO,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAAC;CAChE;AAED,wBAAgB,mBAAmB,CACjC,OAAO,EAAE,oBAAoB,GAC5B,aAAa,CAkJf"}
@@ -0,0 +1,5 @@
1
+ export * from './client.js';
2
+ export * from './registry.js';
3
+ export * from './signing.js';
4
+ export * from './types.js';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,eAAe,CAAC;AAC9B,cAAc,cAAc,CAAC;AAC7B,cAAc,YAAY,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,169 @@
1
+ import { SUPPORT_API_BASE_PATH, SUPPORT_ATTACHMENT_MIME_TYPES, SUPPORT_CATEGORIES, SUPPORT_CLIENT_STATUSES, SUPPORT_CONTENT_SHA256_HEADER, SUPPORT_DEFAULT_CATEGORY, SUPPORT_LIMITS, SUPPORT_PRODUCT_HEADER, SUPPORT_SEVERITY_HINTS, SUPPORT_SIGNATURE_HEADER, SUPPORT_TIMESTAMP_HEADER, adminSummaryToCaseView, isSupportAttachmentId, isSupportExternalUserId, normalizeSupportCategory, supportAttachmentKind, timelineEntryToItemView, validateSupportDiagnostics } from "./types.js";
2
+ import { createHmac, timingSafeEqual } from "node:crypto";
3
+ //#region src/signing.ts
4
+ var SUPPORT_MAX_CLOCK_SKEW_SECONDS = 300;
5
+ var SIGNATURE_PATTERN = /^v1=([0-9a-f]{64})$/;
6
+ var TIMESTAMP_PATTERN = /^\d{1,12}$/;
7
+ function canonicalHmac(secret, timestamp, method, pathWithQuery, body) {
8
+ return createHmac("sha256", secret).update(`${timestamp}
9
+ ${method.toUpperCase()}
10
+ ${pathWithQuery}
11
+ `, "utf8").update(body).digest();
12
+ }
13
+ function signSupportRequest(productKey, input) {
14
+ const timestamp = String(input.timestamp ?? Math.floor(Date.now() / 1e3));
15
+ const digest = canonicalHmac(input.secret, timestamp, input.method, input.pathWithQuery, input.body ?? "");
16
+ return {
17
+ [SUPPORT_PRODUCT_HEADER]: productKey,
18
+ [SUPPORT_TIMESTAMP_HEADER]: timestamp,
19
+ [SUPPORT_SIGNATURE_HEADER]: `v1=${digest.toString("hex")}`
20
+ };
21
+ }
22
+ function verifySupportSignature(input) {
23
+ const timestamp = input.timestampHeader ?? "";
24
+ const match = (input.signatureHeader ?? "").match(SIGNATURE_PATTERN);
25
+ if (!TIMESTAMP_PATTERN.test(timestamp) || !match) return false;
26
+ const nowSeconds = Math.floor((input.now ?? /* @__PURE__ */ new Date()).getTime() / 1e3);
27
+ if (Math.abs(nowSeconds - Number(timestamp)) > 300) return false;
28
+ const provided = Buffer.from(match[1], "hex");
29
+ let verified = false;
30
+ for (const secret of input.secrets.filter(Boolean)) verified = timingSafeEqual(provided, canonicalHmac(secret, timestamp, input.method, input.pathWithQuery, input.body ?? "")) || verified;
31
+ return verified;
32
+ }
33
+ //#endregion
34
+ //#region src/client.ts
35
+ var SupportApiError = class extends Error {
36
+ constructor(status, code) {
37
+ super(`Work support API responded ${status}: ${code}`);
38
+ this.status = status;
39
+ this.code = code;
40
+ this.name = "SupportApiError";
41
+ }
42
+ status;
43
+ code;
44
+ };
45
+ function assertExternalUserId(value) {
46
+ if (!isSupportExternalUserId(value)) throw new SupportApiError(400, "externalUserId is invalid");
47
+ }
48
+ function createSupportClient(options) {
49
+ const doFetch = options.fetch ?? fetch;
50
+ const origin = options.baseUrl.replace(/\/+$/, "");
51
+ async function send(method, pathWithQuery, body, extraHeaders = {}) {
52
+ const headers = signSupportRequest(options.productKey, {
53
+ secret: options.secret,
54
+ method,
55
+ pathWithQuery,
56
+ body,
57
+ timestamp: options.now ? Math.floor(options.now() / 1e3) : void 0
58
+ });
59
+ if (typeof body === "string") headers["content-type"] = "application/json";
60
+ const response = await doFetch(`${origin}${pathWithQuery}`, {
61
+ method,
62
+ headers: {
63
+ ...headers,
64
+ ...extraHeaders
65
+ },
66
+ body
67
+ });
68
+ if (!response.ok) {
69
+ let parsed = null;
70
+ try {
71
+ parsed = await response.json();
72
+ } catch {
73
+ parsed = null;
74
+ }
75
+ const code = parsed && typeof parsed === "object" && "error" in parsed ? String(parsed.error) : "request failed";
76
+ throw new SupportApiError(response.status, code);
77
+ }
78
+ return response;
79
+ }
80
+ async function call(method, pathWithQuery, body) {
81
+ const response = await send(method, pathWithQuery, body);
82
+ try {
83
+ return await response.json();
84
+ } catch {
85
+ return null;
86
+ }
87
+ }
88
+ return {
89
+ submit: (request) => call("POST", SUPPORT_API_BASE_PATH, JSON.stringify(request)),
90
+ getSubmission: (submissionId, options2 = {}) => {
91
+ const qs = options2.externalUserId ? `?${new URLSearchParams({ externalUserId: options2.externalUserId })}` : "";
92
+ return call("GET", `${SUPPORT_API_BASE_PATH}/submissions/${encodeURIComponent(submissionId)}${qs}`);
93
+ },
94
+ replyToSubmission: (submissionId, request) => call("POST", `${SUPPORT_API_BASE_PATH}/submissions/${encodeURIComponent(submissionId)}/messages`, JSON.stringify(request)),
95
+ listUserSubmissions: async (externalUserId, query = {}) => {
96
+ assertExternalUserId(externalUserId);
97
+ const params = new URLSearchParams();
98
+ if (query.limit !== void 0) params.set("limit", String(query.limit));
99
+ if (query.cursor) params.set("cursor", query.cursor);
100
+ if (query.since) params.set("since", query.since);
101
+ const qs = params.toString();
102
+ return call("GET", `${SUPPORT_API_BASE_PATH}/users/${encodeURIComponent(externalUserId)}/submissions${qs ? `?${qs}` : ""}`);
103
+ },
104
+ claimUserSubmissions: async (request) => {
105
+ assertExternalUserId(request.fromExternalUserId);
106
+ return call("POST", `${SUPPORT_API_BASE_PATH}/users/claim`, JSON.stringify(request));
107
+ },
108
+ uploadAttachment: async (bytes, uploadOptions) => {
109
+ return await (await send("POST", `${SUPPORT_API_BASE_PATH}/attachments`, bytes, {
110
+ "content-type": uploadOptions.contentType,
111
+ ...uploadOptions.sha256 ? { [SUPPORT_CONTENT_SHA256_HEADER]: uploadOptions.sha256 } : {}
112
+ })).json();
113
+ },
114
+ transcribe: async (bytes, transcribeOptions) => {
115
+ return await (await send("POST", `${SUPPORT_API_BASE_PATH}/transcribe`, bytes, { "content-type": transcribeOptions.contentType })).json();
116
+ },
117
+ downloadAttachment: async (caseNumber, attachmentId) => {
118
+ if (!isSupportAttachmentId(attachmentId)) throw new SupportApiError(400, "attachmentId is invalid");
119
+ const response = await send("GET", `${SUPPORT_API_BASE_PATH}/admin/${encodeURIComponent(caseNumber)}/attachments/${attachmentId}`);
120
+ return {
121
+ bytes: new Uint8Array(await response.arrayBuffer()),
122
+ contentType: response.headers.get("content-type") ?? "application/octet-stream"
123
+ };
124
+ },
125
+ listCases: (query = {}) => {
126
+ const params = new URLSearchParams();
127
+ if (query.limit !== void 0) params.set("limit", String(query.limit));
128
+ if (query.cursor) params.set("cursor", query.cursor);
129
+ if (query.since) params.set("since", query.since);
130
+ const qs = params.toString();
131
+ return call("GET", `${SUPPORT_API_BASE_PATH}/admin${qs ? `?${qs}` : ""}`);
132
+ },
133
+ getCase: (caseNumber) => call("GET", `${SUPPORT_API_BASE_PATH}/admin/${encodeURIComponent(caseNumber)}`)
134
+ };
135
+ }
136
+ //#endregion
137
+ //#region src/registry.ts
138
+ var SUPPORT_REGISTRY_BASE_PATH = "/api/support-registry";
139
+ var SUPPORT_REGISTRY_ENSURE_PATH = `${SUPPORT_REGISTRY_BASE_PATH}/products`;
140
+ var SUPPORT_REGISTRY_DISABLE_PATH = `${SUPPORT_REGISTRY_BASE_PATH}/products/disable`;
141
+ var SUPPORT_REGISTRY_RETIRE_PATH = `${SUPPORT_REGISTRY_BASE_PATH}/products/retire`;
142
+ var SUPPORT_REGISTRY_ROTATE_PATH = `${SUPPORT_REGISTRY_BASE_PATH}/admin/rotate`;
143
+ var SUPPORT_REGISTRY_ADOPT_PATH = `${SUPPORT_REGISTRY_BASE_PATH}/admin/adopt`;
144
+ var SUPPORT_PRODUCT_KEY_PATTERN = /^[a-z0-9][a-z0-9-]{0,31}$/;
145
+ function isSupportProductKey(value) {
146
+ return typeof value === "string" && SUPPORT_PRODUCT_KEY_PATTERN.test(value);
147
+ }
148
+ var SUPPORT_REGISTRY_ROTATION_OVERLAP_SECONDS = 3600;
149
+ var SUPPORT_REGISTRY_ERROR_CODES = [
150
+ "invalid_request",
151
+ "unauthorized",
152
+ "forbidden",
153
+ "unavailable",
154
+ "unknown_deployment_target",
155
+ "project_mismatch",
156
+ "binding_not_approved",
157
+ "target_deleted",
158
+ "key_in_environment_registry",
159
+ "key_in_store",
160
+ "binding_in_use",
161
+ "not_found",
162
+ "not_active",
163
+ "retry",
164
+ "failed"
165
+ ];
166
+ //#endregion
167
+ export { SUPPORT_API_BASE_PATH, SUPPORT_ATTACHMENT_MIME_TYPES, SUPPORT_CATEGORIES, SUPPORT_CLIENT_STATUSES, SUPPORT_CONTENT_SHA256_HEADER, SUPPORT_DEFAULT_CATEGORY, SUPPORT_LIMITS, SUPPORT_MAX_CLOCK_SKEW_SECONDS, SUPPORT_PRODUCT_HEADER, SUPPORT_PRODUCT_KEY_PATTERN, SUPPORT_REGISTRY_ADOPT_PATH, SUPPORT_REGISTRY_BASE_PATH, SUPPORT_REGISTRY_DISABLE_PATH, SUPPORT_REGISTRY_ENSURE_PATH, SUPPORT_REGISTRY_ERROR_CODES, SUPPORT_REGISTRY_RETIRE_PATH, SUPPORT_REGISTRY_ROTATE_PATH, SUPPORT_REGISTRY_ROTATION_OVERLAP_SECONDS, SUPPORT_SEVERITY_HINTS, SUPPORT_SIGNATURE_HEADER, SUPPORT_TIMESTAMP_HEADER, SupportApiError, adminSummaryToCaseView, createSupportClient, isSupportAttachmentId, isSupportExternalUserId, isSupportProductKey, normalizeSupportCategory, signSupportRequest, supportAttachmentKind, timelineEntryToItemView, validateSupportDiagnostics, verifySupportSignature };
168
+
169
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["options"],"sources":["../src/signing.ts","../src/client.ts","../src/registry.ts"],"sourcesContent":["import { createHmac, timingSafeEqual } from 'node:crypto';\nimport {\n SUPPORT_PRODUCT_HEADER,\n SUPPORT_SIGNATURE_HEADER,\n SUPPORT_TIMESTAMP_HEADER,\n} from './types.js';\n\nexport const SUPPORT_MAX_CLOCK_SKEW_SECONDS = 300;\n\nconst SIGNATURE_PATTERN = /^v1=([0-9a-f]{64})$/;\nconst TIMESTAMP_PATTERN = /^\\d{1,12}$/;\n\nexport interface SupportSignInput {\n secret: string;\n method: string;\n /** Request path plus query string exactly as sent, e.g. `/api/public/support-requests/admin?limit=20`. */\n pathWithQuery: string;\n /** Raw request body; empty for GET. */\n body?: string | Uint8Array;\n /** Unix seconds. Defaults to now. */\n timestamp?: number;\n}\n\nfunction canonicalHmac(\n secret: string,\n timestamp: string,\n method: string,\n pathWithQuery: string,\n body: string | Uint8Array,\n): Buffer {\n // method + path + query are bound into the signature so a signature for one\n // endpoint (or a bodiless GET) can never be replayed against another.\n return createHmac('sha256', secret)\n .update(`${timestamp}\\n${method.toUpperCase()}\\n${pathWithQuery}\\n`, 'utf8')\n .update(body)\n .digest();\n}\n\n/** Produces the three headers a signed request must carry. */\nexport function signSupportRequest(\n productKey: string,\n input: SupportSignInput,\n): Record<string, string> {\n const timestamp = String(input.timestamp ?? Math.floor(Date.now() / 1000));\n const digest = canonicalHmac(\n input.secret,\n timestamp,\n input.method,\n input.pathWithQuery,\n input.body ?? '',\n );\n return {\n [SUPPORT_PRODUCT_HEADER]: productKey,\n [SUPPORT_TIMESTAMP_HEADER]: timestamp,\n [SUPPORT_SIGNATURE_HEADER]: `v1=${digest.toString('hex')}`,\n };\n}\n\nexport interface SupportVerifyInput {\n /** Current secret, then optionally the previous one during rotation. */\n secrets: string[];\n method: string;\n pathWithQuery: string;\n body?: string | Uint8Array;\n timestampHeader: string | null;\n signatureHeader: string | null;\n now?: Date;\n}\n\n/** Server-side check; true only for a fresh, correctly signed request. */\nexport function verifySupportSignature(input: SupportVerifyInput): boolean {\n const timestamp = input.timestampHeader ?? '';\n const match = (input.signatureHeader ?? '').match(SIGNATURE_PATTERN);\n if (!TIMESTAMP_PATTERN.test(timestamp) || !match) return false;\n const nowSeconds = Math.floor((input.now ?? new Date()).getTime() / 1000);\n if (Math.abs(nowSeconds - Number(timestamp)) > SUPPORT_MAX_CLOCK_SKEW_SECONDS)\n return false;\n const provided = Buffer.from(match[1], 'hex');\n let verified = false;\n for (const secret of input.secrets.filter(Boolean)) {\n const expected = canonicalHmac(\n secret,\n timestamp,\n input.method,\n input.pathWithQuery,\n input.body ?? '',\n );\n verified = timingSafeEqual(provided, expected) || verified;\n }\n return verified;\n}\n","import { signSupportRequest } from './signing.js';\nimport {\n isSupportAttachmentId,\n isSupportExternalUserId,\n SUPPORT_API_BASE_PATH,\n SUPPORT_CONTENT_SHA256_HEADER,\n type SupportAdminCaseResponse,\n type SupportAdminListQuery,\n type SupportAdminListResponse,\n type SupportClaimRequest,\n type SupportClaimResponse,\n type SupportReplyRequest,\n type SupportReplyResponse,\n type SupportSubmissionView,\n type SupportSubmitRequest,\n type SupportSubmitResponse,\n type SupportTranscribeResponse,\n type SupportUploadResponse,\n type SupportUserSubmissionsQuery,\n type SupportUserSubmissionsResponse,\n} from './types.js';\n\nexport class SupportApiError extends Error {\n constructor(\n public readonly status: number,\n public readonly code: string,\n ) {\n super(`Work support API responded ${status}: ${code}`);\n this.name = 'SupportApiError';\n }\n}\n\n/** Rejects ids the server would reject, before they reach a signed URL (`.`/`..` would be normalised away). */\nfunction assertExternalUserId(value: string): void {\n if (!isSupportExternalUserId(value))\n throw new SupportApiError(400, 'externalUserId is invalid');\n}\n\nexport interface SupportClientOptions {\n /** Origin of the Work deployment, e.g. `https://work.happyvertical.com`. */\n baseUrl: string;\n productKey: string;\n secret: string;\n fetch?: typeof fetch;\n now?: () => number;\n}\n\nexport interface SupportClient {\n submit(request: SupportSubmitRequest): Promise<SupportSubmitResponse>;\n /** Submitter read-back: the client-visible timeline for one submission. */\n getSubmission(\n submissionId: string,\n options?: { externalUserId?: string },\n ): Promise<SupportSubmissionView>;\n /** Post the user's follow-up to their own submission. Idempotent on `messageId`. */\n replyToSubmission(\n submissionId: string,\n request: SupportReplyRequest,\n ): Promise<SupportReplyResponse>;\n /** The user's own submissions, newest activity first. Scoped to this product. */\n listUserSubmissions(\n externalUserId: string,\n query?: SupportUserSubmissionsQuery,\n ): Promise<SupportUserSubmissionsResponse>;\n /** Move an anonymous user's submissions to an account. Idempotent. */\n claimUserSubmissions(\n request: SupportClaimRequest,\n ): Promise<SupportClaimResponse>;\n /**\n * Uploads one binary attachment (png, jpeg, webp, webm/wav/ogg/mp4 audio) and\n * returns its id for `attachmentIds`. The HMAC covers the bytes. `contentType`\n * must match what Work sniffs from them (parameters such as `;codecs=opus`\n * are ignored); `sha256` is an optional lowercase-hex integrity check.\n */\n uploadAttachment(\n bytes: Uint8Array,\n options: { contentType: string; sha256?: string },\n ): Promise<SupportUploadResponse>;\n /**\n * Transcribes one short voice clip (at most `SUPPORT_LIMITS.transcribeMaxSeconds`\n * seconds and `transcribeMaxBytes` bytes; same media types and `contentType` rule\n * as `uploadAttachment`). Nothing is stored. Counts against this product's daily\n * transcription budget: a spent budget answers 429.\n */\n transcribe(\n bytes: Uint8Array,\n options: { contentType: string },\n ): Promise<SupportTranscribeResponse>;\n /**\n * Product-admin tier: the bytes of one attachment on one of this product's\n * cases. Work checks the product and the case binding; the product's own\n * backend must gate which admins may call it.\n */\n downloadAttachment(\n caseNumber: string,\n attachmentId: string,\n ): Promise<{ bytes: Uint8Array; contentType: string }>;\n /** Product-admin tier. The product's own backend must gate who may call it. */\n listCases(query?: SupportAdminListQuery): Promise<SupportAdminListResponse>;\n getCase(caseNumber: string): Promise<SupportAdminCaseResponse>;\n}\n\nexport function createSupportClient(\n options: SupportClientOptions,\n): SupportClient {\n const doFetch = options.fetch ?? fetch;\n const origin = options.baseUrl.replace(/\\/+$/, '');\n\n async function send(\n method: 'GET' | 'POST',\n pathWithQuery: string,\n body?: string | Uint8Array,\n extraHeaders: Record<string, string> = {},\n ): Promise<Response> {\n const headers: Record<string, string> = signSupportRequest(\n options.productKey,\n {\n secret: options.secret,\n method,\n pathWithQuery,\n body,\n timestamp: options.now ? Math.floor(options.now() / 1000) : undefined,\n },\n );\n if (typeof body === 'string') headers['content-type'] = 'application/json';\n const response = await doFetch(`${origin}${pathWithQuery}`, {\n method,\n headers: { ...headers, ...extraHeaders },\n body: body as RequestInit['body'],\n });\n if (!response.ok) {\n let parsed: unknown = null;\n try {\n parsed = await response.json();\n } catch {\n parsed = null;\n }\n const code =\n parsed && typeof parsed === 'object' && 'error' in parsed\n ? String((parsed as { error: unknown }).error)\n : 'request failed';\n throw new SupportApiError(response.status, code);\n }\n return response;\n }\n\n async function call<T>(\n method: 'GET' | 'POST',\n pathWithQuery: string,\n body?: string,\n ): Promise<T> {\n const response = await send(method, pathWithQuery, body);\n try {\n return (await response.json()) as T;\n } catch {\n return null as T;\n }\n }\n\n return {\n submit: (request) =>\n call('POST', SUPPORT_API_BASE_PATH, JSON.stringify(request)),\n getSubmission: (submissionId, options = {}) => {\n const qs = options.externalUserId\n ? `?${new URLSearchParams({ externalUserId: options.externalUserId })}`\n : '';\n return call(\n 'GET',\n `${SUPPORT_API_BASE_PATH}/submissions/${encodeURIComponent(submissionId)}${qs}`,\n );\n },\n replyToSubmission: (submissionId, request) =>\n call(\n 'POST',\n `${SUPPORT_API_BASE_PATH}/submissions/${encodeURIComponent(submissionId)}/messages`,\n JSON.stringify(request),\n ),\n listUserSubmissions: async (externalUserId, query = {}) => {\n assertExternalUserId(externalUserId);\n const params = new URLSearchParams();\n if (query.limit !== undefined) params.set('limit', String(query.limit));\n if (query.cursor) params.set('cursor', query.cursor);\n if (query.since) params.set('since', query.since);\n const qs = params.toString();\n return call(\n 'GET',\n `${SUPPORT_API_BASE_PATH}/users/${encodeURIComponent(externalUserId)}/submissions${qs ? `?${qs}` : ''}`,\n );\n },\n claimUserSubmissions: async (request) => {\n assertExternalUserId(request.fromExternalUserId);\n return call(\n 'POST',\n `${SUPPORT_API_BASE_PATH}/users/claim`,\n JSON.stringify(request),\n );\n },\n uploadAttachment: async (bytes, uploadOptions) => {\n const response = await send(\n 'POST',\n `${SUPPORT_API_BASE_PATH}/attachments`,\n bytes,\n {\n 'content-type': uploadOptions.contentType,\n ...(uploadOptions.sha256\n ? { [SUPPORT_CONTENT_SHA256_HEADER]: uploadOptions.sha256 }\n : {}),\n },\n );\n return (await response.json()) as SupportUploadResponse;\n },\n transcribe: async (bytes, transcribeOptions) => {\n const response = await send(\n 'POST',\n `${SUPPORT_API_BASE_PATH}/transcribe`,\n bytes,\n {\n 'content-type': transcribeOptions.contentType,\n },\n );\n return (await response.json()) as SupportTranscribeResponse;\n },\n downloadAttachment: async (caseNumber, attachmentId) => {\n if (!isSupportAttachmentId(attachmentId)) {\n throw new SupportApiError(400, 'attachmentId is invalid');\n }\n const response = await send(\n 'GET',\n `${SUPPORT_API_BASE_PATH}/admin/${encodeURIComponent(caseNumber)}/attachments/${attachmentId}`,\n );\n return {\n bytes: new Uint8Array(await response.arrayBuffer()),\n contentType:\n response.headers.get('content-type') ?? 'application/octet-stream',\n };\n },\n listCases: (query = {}) => {\n const params = new URLSearchParams();\n if (query.limit !== undefined) params.set('limit', String(query.limit));\n if (query.cursor) params.set('cursor', query.cursor);\n if (query.since) params.set('since', query.since);\n const qs = params.toString();\n return call('GET', `${SUPPORT_API_BASE_PATH}/admin${qs ? `?${qs}` : ''}`);\n },\n getCase: (caseNumber) =>\n call(\n 'GET',\n `${SUPPORT_API_BASE_PATH}/admin/${encodeURIComponent(caseNumber)}`,\n ),\n };\n}\n","/**\n * Hosted support registry API (#703, decision 0009 in happyvertical-operator).\n *\n * Work owns who may authenticate to the signed product support API. The\n * operator's `support` binding calls the operator routes below with a bearer\n * token (a dedicated Work service credential, valid on these routes only) to\n * obtain a hosted product's key and secret; Work administrators rotate and\n * adopt products through the admin routes from a signed-in session.\n *\n * Nothing here carries a tenant id: Work takes the tenant from the app's\n * deployment target, never from the caller.\n */\n\nexport const SUPPORT_REGISTRY_BASE_PATH = '/api/support-registry';\n\n/** `PUT`: ensure a product for one app binding (idempotent), answers the key and current secret. */\nexport const SUPPORT_REGISTRY_ENSURE_PATH = `${SUPPORT_REGISTRY_BASE_PATH}/products`;\n/** `POST`: stop accepting the product's signatures; cases stay. Idempotent. */\nexport const SUPPORT_REGISTRY_DISABLE_PATH = `${SUPPORT_REGISTRY_BASE_PATH}/products/disable`;\n/** `POST`: disable for a deleted app; the key is never issued again. Idempotent. */\nexport const SUPPORT_REGISTRY_RETIRE_PATH = `${SUPPORT_REGISTRY_BASE_PATH}/products/retire`;\n/** `POST`, Work administrator session: rotate a product's secret with an overlap. */\nexport const SUPPORT_REGISTRY_ROTATE_PATH = `${SUPPORT_REGISTRY_BASE_PATH}/admin/rotate`;\n/** `POST`, Work administrator session: move an environment-registry product into the store. */\nexport const SUPPORT_REGISTRY_ADOPT_PATH = `${SUPPORT_REGISTRY_BASE_PATH}/admin/adopt`;\n\n/** The product key shape the registry accepts (at most 32 characters). */\nexport const SUPPORT_PRODUCT_KEY_PATTERN = /^[a-z0-9][a-z0-9-]{0,31}$/;\n\nexport function isSupportProductKey(value: unknown): value is string {\n return typeof value === 'string' && SUPPORT_PRODUCT_KEY_PATTERN.test(value);\n}\n\n/** Overlap during which the previous secret is still accepted after a rotation. */\nexport const SUPPORT_REGISTRY_ROTATION_OVERLAP_SECONDS = 60 * 60;\n\nexport interface SupportRegistryEnsureRequest {\n /** The hosted app's platform name. */\n platformName: string;\n /** The app's `support` binding name. */\n bindingName: string;\n /** The app's `happyvertical.com/work-project-id`; must match the deployment target's project. */\n projectId: string;\n /**\n * The operator's proposed key. Work uses it when it is free and answers with\n * a different key when it is not; the caller injects whatever key comes back.\n */\n productKey?: string;\n}\n\nexport interface SupportRegistryEnsureResponse {\n productKey: string;\n /** The current secret, returned on every call; treat as a credential. */\n secret: string;\n}\n\nexport interface SupportRegistryLifecycleRequest {\n platformName: string;\n bindingName: string;\n}\n\nexport interface SupportRegistryLifecycleResponse {\n /** `absent` when Work holds no live product for the binding; the call is still a success. */\n state: 'disabled' | 'retired' | 'absent';\n productKey?: string;\n}\n\nexport interface SupportRegistryRotateRequest {\n productKey: string;\n}\n\nexport interface SupportRegistryRotateResponse {\n productKey: string;\n /** ISO time at which the previous secret stops being accepted. */\n previousExpiresAt: string;\n}\n\nexport interface SupportRegistryAdoptRequest {\n /** The environment-registry key to move; its key, tenant and project are kept. */\n productKey: string;\n platformName: string;\n bindingName: string;\n}\n\nexport interface SupportRegistryAdoptResponse {\n productKey: string;\n state: 'active';\n}\n\n/** Machine codes in `SupportRegistryErrorBody.error`. Never a secret or a tenant id. */\nexport const SUPPORT_REGISTRY_ERROR_CODES = [\n 'invalid_request',\n 'unauthorized',\n 'forbidden',\n 'unavailable',\n 'unknown_deployment_target',\n 'project_mismatch',\n 'binding_not_approved',\n 'target_deleted',\n 'key_in_environment_registry',\n 'key_in_store',\n 'binding_in_use',\n 'not_found',\n 'not_active',\n 'retry',\n 'failed',\n] as const;\nexport type SupportRegistryErrorCode =\n (typeof SUPPORT_REGISTRY_ERROR_CODES)[number];\n\nexport interface SupportRegistryErrorBody {\n error: SupportRegistryErrorCode;\n}\n"],"mappings":";;;AAOO,IAAM,iCAAiC;AAE9C,IAAM,oBAAoB;AAC1B,IAAM,oBAAoB;AAa1B,SAAS,cACP,QACA,WACA,QACA,eACA,MACQ;CAGR,OAAO,WAAW,UAAU,MAAM,CAAA,CAC/B,OAAO,GAAG,UAAS;EAAK,OAAO,YAAY,EAAC;EAAK,cAAa;GAAM,MAAM,CAAA,CAC1E,OAAO,IAAI,CAAA,CACX,OAAO;AACZ;AAGO,SAAS,mBACd,YACA,OACwB;CACxB,MAAM,YAAY,OAAO,MAAM,aAAa,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI,CAAC;CACzE,MAAM,SAAS,cACb,MAAM,QACN,WACA,MAAM,QACN,MAAM,eACN,MAAM,QAAQ,EAChB;CACA,OAAO;GACJ,yBAAyB;GACzB,2BAA2B;GAC3B,2BAA2B,MAAM,OAAO,SAAS,KAAK;CACzD;AACF;AAcO,SAAS,uBAAuB,OAAoC;CACzE,MAAM,YAAY,MAAM,mBAAmB;CAC3C,MAAM,SAAS,MAAM,mBAAmB,GAAA,CAAI,MAAM,iBAAiB;CACnE,IAAI,CAAC,kBAAkB,KAAK,SAAS,KAAK,CAAC,OAAO,OAAO;CACzD,MAAM,aAAa,KAAK,OAAO,MAAM,uBAAO,IAAI,KAAK,EAAA,CAAG,QAAQ,IAAI,GAAI;CACxE,IAAI,KAAK,IAAI,aAAa,OAAO,SAAS,CAAC,IAAA,KACzC,OAAO;CACT,MAAM,WAAW,OAAO,KAAK,MAAM,IAAI,KAAK;CAC5C,IAAI,WAAW;CACf,KAAA,MAAW,UAAU,MAAM,QAAQ,OAAO,OAAO,GAQ/C,WAAW,gBAAgB,UAPV,cACf,QACA,WACA,MAAM,QACN,MAAM,eACN,MAAM,QAAQ,EAEqB,CAAQ,KAAK;C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@@
1
+ {
2
+ "version": "1.0.0",
3
+ "timestamp": 0,
4
+ "packageName": "@happyvertical/smrt-support-contract",
5
+ "packageVersion": "0.74.5",
6
+ "objects": {},
7
+ "moduleType": "smrt",
8
+ "smrtDependencies": [
9
+ "@happyvertical/smrt-core"
10
+ ],
11
+ "schemaFingerprint": "4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945",
12
+ "stampsConstructors": true
13
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Hosted support registry API (#703, decision 0009 in happyvertical-operator).
3
+ *
4
+ * Work owns who may authenticate to the signed product support API. The
5
+ * operator's `support` binding calls the operator routes below with a bearer
6
+ * token (a dedicated Work service credential, valid on these routes only) to
7
+ * obtain a hosted product's key and secret; Work administrators rotate and
8
+ * adopt products through the admin routes from a signed-in session.
9
+ *
10
+ * Nothing here carries a tenant id: Work takes the tenant from the app's
11
+ * deployment target, never from the caller.
12
+ */
13
+ export declare const SUPPORT_REGISTRY_BASE_PATH = "/api/support-registry";
14
+ /** `PUT`: ensure a product for one app binding (idempotent), answers the key and current secret. */
15
+ export declare const SUPPORT_REGISTRY_ENSURE_PATH = "/api/support-registry/products";
16
+ /** `POST`: stop accepting the product's signatures; cases stay. Idempotent. */
17
+ export declare const SUPPORT_REGISTRY_DISABLE_PATH = "/api/support-registry/products/disable";
18
+ /** `POST`: disable for a deleted app; the key is never issued again. Idempotent. */
19
+ export declare const SUPPORT_REGISTRY_RETIRE_PATH = "/api/support-registry/products/retire";
20
+ /** `POST`, Work administrator session: rotate a product's secret with an overlap. */
21
+ export declare const SUPPORT_REGISTRY_ROTATE_PATH = "/api/support-registry/admin/rotate";
22
+ /** `POST`, Work administrator session: move an environment-registry product into the store. */
23
+ export declare const SUPPORT_REGISTRY_ADOPT_PATH = "/api/support-registry/admin/adopt";
24
+ /** The product key shape the registry accepts (at most 32 characters). */
25
+ export declare const SUPPORT_PRODUCT_KEY_PATTERN: RegExp;
26
+ export declare function isSupportProductKey(value: unknown): value is string;
27
+ /** Overlap during which the previous secret is still accepted after a rotation. */
28
+ export declare const SUPPORT_REGISTRY_ROTATION_OVERLAP_SECONDS: number;
29
+ export interface SupportRegistryEnsureRequest {
30
+ /** The hosted app's platform name. */
31
+ platformName: string;
32
+ /** The app's `support` binding name. */
33
+ bindingName: string;
34
+ /** The app's `happyvertical.com/work-project-id`; must match the deployment target's project. */
35
+ projectId: string;
36
+ /**
37
+ * The operator's proposed key. Work uses it when it is free and answers with
38
+ * a different key when it is not; the caller injects whatever key comes back.
39
+ */
40
+ productKey?: string;
41
+ }
42
+ export interface SupportRegistryEnsureResponse {
43
+ productKey: string;
44
+ /** The current secret, returned on every call; treat as a credential. */
45
+ secret: string;
46
+ }
47
+ export interface SupportRegistryLifecycleRequest {
48
+ platformName: string;
49
+ bindingName: string;
50
+ }
51
+ export interface SupportRegistryLifecycleResponse {
52
+ /** `absent` when Work holds no live product for the binding; the call is still a success. */
53
+ state: 'disabled' | 'retired' | 'absent';
54
+ productKey?: string;
55
+ }
56
+ export interface SupportRegistryRotateRequest {
57
+ productKey: string;
58
+ }
59
+ export interface SupportRegistryRotateResponse {
60
+ productKey: string;
61
+ /** ISO time at which the previous secret stops being accepted. */
62
+ previousExpiresAt: string;
63
+ }
64
+ export interface SupportRegistryAdoptRequest {
65
+ /** The environment-registry key to move; its key, tenant and project are kept. */
66
+ productKey: string;
67
+ platformName: string;
68
+ bindingName: string;
69
+ }
70
+ export interface SupportRegistryAdoptResponse {
71
+ productKey: string;
72
+ state: 'active';
73
+ }
74
+ /** Machine codes in `SupportRegistryErrorBody.error`. Never a secret or a tenant id. */
75
+ export declare const SUPPORT_REGISTRY_ERROR_CODES: readonly ["invalid_request", "unauthorized", "forbidden", "unavailable", "unknown_deployment_target", "project_mismatch", "binding_not_approved", "target_deleted", "key_in_environment_registry", "key_in_store", "binding_in_use", "not_found", "not_active", "retry", "failed"];
76
+ export type SupportRegistryErrorCode = (typeof SUPPORT_REGISTRY_ERROR_CODES)[number];
77
+ export interface SupportRegistryErrorBody {
78
+ error: SupportRegistryErrorCode;
79
+ }
80
+ //# sourceMappingURL=registry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../src/registry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,eAAO,MAAM,0BAA0B,0BAA0B,CAAC;AAElE,oGAAoG;AACpG,eAAO,MAAM,4BAA4B,mCAA2C,CAAC;AACrF,+EAA+E;AAC/E,eAAO,MAAM,6BAA6B,2CAAmD,CAAC;AAC9F,oFAAoF;AACpF,eAAO,MAAM,4BAA4B,0CAAkD,CAAC;AAC5F,qFAAqF;AACrF,eAAO,MAAM,4BAA4B,uCAA+C,CAAC;AACzF,+FAA+F;AAC/F,eAAO,MAAM,2BAA2B,sCAA8C,CAAC;AAEvF,0EAA0E;AAC1E,eAAO,MAAM,2BAA2B,QAA8B,CAAC;AAEvE,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAEnE;AAED,mFAAmF;AACnF,eAAO,MAAM,yCAAyC,QAAU,CAAC;AAEjE,MAAM,WAAW,4BAA4B;IAC3C,sCAAsC;IACtC,YAAY,EAAE,MAAM,CAAC;IACrB,wCAAwC;IACxC,WAAW,EAAE,MAAM,CAAC;IACpB,iGAAiG;IACjG,SAAS,EAAE,MAAM,CAAC;IAClB;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,6BAA6B;IAC5C,UAAU,EAAE,MAAM,CAAC;IACnB,yEAAyE;IACzE,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,+BAA+B;IAC9C,YAAY,EAAE,MAAM,CAAC;IACrB,WAAW,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,gCAAgC;IAC/C,6FAA6F;IAC7F,KAAK,EAAE,UAAU,GAAG,SAAS,GAAG,QAAQ,CAAC;IACzC,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,4BAA4B;IAC3C,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,6BAA6B;IAC5C,UAAU,EAAE,MAAM,CAAC;IACnB,kEAAkE;IAClE,iBAAiB,EAAE,MAAM,CAAC;CAC3B;AAED,MAAM,WAAW,2BAA2B;IAC1C,kFAAkF;IAClF,UAAU,EAAE,MAAM,CAAC;IACnB,YAAY,EAAE,MAAM,CAAC;IACrB,WAAW,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,4BAA4B;IAC3C,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,EAAE,QAAQ,CAAC;CACjB;AAED,wFAAwF;AACxF,eAAO,MAAM,4BAA4B,oRAgB/B,CAAC;AACX,MAAM,MAAM,wBAAwB,GAClC,CAAC,OAAO,4BAA4B,CAAC,CAAC,MAAM,CAAC,CAAC;AAEhD,MAAM,WAAW,wBAAwB;IACvC,KAAK,EAAE,wBAAwB,CAAC;CACjC"}
@@ -0,0 +1,26 @@
1
+ export declare const SUPPORT_MAX_CLOCK_SKEW_SECONDS = 300;
2
+ export interface SupportSignInput {
3
+ secret: string;
4
+ method: string;
5
+ /** Request path plus query string exactly as sent, e.g. `/api/public/support-requests/admin?limit=20`. */
6
+ pathWithQuery: string;
7
+ /** Raw request body; empty for GET. */
8
+ body?: string | Uint8Array;
9
+ /** Unix seconds. Defaults to now. */
10
+ timestamp?: number;
11
+ }
12
+ /** Produces the three headers a signed request must carry. */
13
+ export declare function signSupportRequest(productKey: string, input: SupportSignInput): Record<string, string>;
14
+ export interface SupportVerifyInput {
15
+ /** Current secret, then optionally the previous one during rotation. */
16
+ secrets: string[];
17
+ method: string;
18
+ pathWithQuery: string;
19
+ body?: string | Uint8Array;
20
+ timestampHeader: string | null;
21
+ signatureHeader: string | null;
22
+ now?: Date;
23
+ }
24
+ /** Server-side check; true only for a fresh, correctly signed request. */
25
+ export declare function verifySupportSignature(input: SupportVerifyInput): boolean;
26
+ //# sourceMappingURL=signing.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"signing.d.ts","sourceRoot":"","sources":["../src/signing.ts"],"names":[],"mappings":"AAOA,eAAO,MAAM,8BAA8B,MAAM,CAAC;AAKlD,MAAM,WAAW,gBAAgB;IAC/B,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,0GAA0G;IAC1G,aAAa,EAAE,MAAM,CAAC;IACtB,uCAAuC;IACvC,IAAI,CAAC,EAAE,MAAM,GAAG,UAAU,CAAC;IAC3B,qCAAqC;IACrC,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAiBD,8DAA8D;AAC9D,wBAAgB,kBAAkB,CAChC,UAAU,EAAE,MAAM,EAClB,KAAK,EAAE,gBAAgB,GACtB,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAcxB;AAED,MAAM,WAAW,kBAAkB;IACjC,wEAAwE;IACxE,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,aAAa,EAAE,MAAM,CAAC;IACtB,IAAI,CAAC,EAAE,MAAM,GAAG,UAAU,CAAC;IAC3B,eAAe,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,eAAe,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,GAAG,CAAC,EAAE,IAAI,CAAC;CACZ;AAED,0EAA0E;AAC1E,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,kBAAkB,GAAG,OAAO,CAoBzE"}
@@ -0,0 +1,46 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "sensitiveFieldsExcluded": true,
4
+ "generatedAt": "1970-01-01T00:00:00.000Z",
5
+ "packageName": "@happyvertical/smrt-support-contract",
6
+ "packageVersion": "0.74.5",
7
+ "sourceManifestPath": "dist/manifest.json",
8
+ "agentDocPath": "AGENTS.md",
9
+ "sourceHashes": {
10
+ "manifest": "c67c1403e5d2223303eb5542cc319028d99c6426ad70180c8b530c081816176e",
11
+ "packageJson": "ddf02cfa645c3a8c819f075fce72f3c749852bafa8418480eeed0a7d44684896",
12
+ "agents": "fdeefc2ac73bfd77656e0abf35f7595c19d99eb36a05f933b9df9e89e9f1853b"
13
+ },
14
+ "exports": [
15
+ "."
16
+ ],
17
+ "dependencies": {
18
+ "@happyvertical/smrt-core": "workspace:*",
19
+ "@types/node": "24.13.6",
20
+ "typescript": "6.0.3",
21
+ "vite": "8.1.6",
22
+ "vitest": "4.1.10"
23
+ },
24
+ "smrtDependencies": [
25
+ "@happyvertical/smrt-core"
26
+ ],
27
+ "sdkDependencies": [],
28
+ "tags": [
29
+ "cross-package"
30
+ ],
31
+ "risks": [
32
+ "sensitive-fields-excluded"
33
+ ],
34
+ "objects": [],
35
+ "surfaces": [],
36
+ "prompts": [],
37
+ "relationshipsV2": {
38
+ "foreignKeyFields": 0,
39
+ "crossPackageRefFields": 0,
40
+ "junctionCollections": 0,
41
+ "hierarchicalObjects": 0,
42
+ "polymorphicAssociations": 0,
43
+ "uuidColumns": 0
44
+ },
45
+ "agentDoc": "# @happyvertical/smrt-support-contract\n\nPublic wire contract for HappyVertical Work's signed product support intake\nAPI: DTOs and limits (`types.ts`), the HMAC signing and verification helper\n(`signing.ts`), the hosted support registry DTOs (`registry.ts`), and a thin\nfetch client (`client.ts`). Work's route handlers import the same types and\nverifier, and `@happyvertical/smrt-product-kit/support` builds on the client,\nso the wire contract has one owner and cannot drift between the two sides.\n\nLifted from `@happyvertical/work-support-contract` 0.3.0\n(happyvertical.com, `packages/work-support-contract`, commit\n`80fb450aca747f10ce98171b5a8758678cc8e2ad`). It is published to the public\nnpm registry so Docker builds resolve it without registry credentials; no\nproduct may vendor a copy.\n\n## Rules\n\n- Zero runtime dependencies beyond `node:crypto` and global `fetch`. It is a\n leaf: no runtime dependency on another smrt package (`smrt-core` is a build-time devDependency only, for the shared vite config).\n- Changes are additive. A new field or route is optional on the wire; a\n signature, header name or path change breaks every deployed product.\n- Never put Work internals (tenant ids, profile ids, AI-run data, internal\n events, compensation) into a DTO. Everything here is product-visible.\n- `registry.ts` DTOs never carry a tenant id.\n- Keep behaviour in step with the Work side when `types.ts`, `signing.ts` or\n the paths change; the signing vectors in `signing.test.ts` pin the format.\n\n## Commands\n\n```bash\npnpm --filter @happyvertical/smrt-support-contract build\npnpm --filter @happyvertical/smrt-support-contract test\npnpm --filter @happyvertical/smrt-support-contract typecheck\n```\n"
46
+ }
@@ -0,0 +1,378 @@
1
+ /**
2
+ * Wire contract for HappyVertical Work's product support API. Every shape here
3
+ * is product-visible: Work never serialises tenant ids, profile ids, internal
4
+ * events, AI-run internals or compensation data through these DTOs.
5
+ */
6
+ export declare const SUPPORT_API_BASE_PATH = "/api/public/support-requests";
7
+ export declare const SUPPORT_PRODUCT_HEADER = "x-hv-support-product";
8
+ export declare const SUPPORT_TIMESTAMP_HEADER = "x-hv-support-timestamp";
9
+ export declare const SUPPORT_SIGNATURE_HEADER = "x-hv-support-signature";
10
+ /**
11
+ * Optional lowercase-hex SHA-256 of an upload's bytes. When sent, Work
12
+ * recomputes the digest and rejects a mismatch (422); it is an integrity
13
+ * check on top of the HMAC, which already covers the body.
14
+ */
15
+ export declare const SUPPORT_CONTENT_SHA256_HEADER = "x-hv-support-content-sha256";
16
+ export declare const SUPPORT_SEVERITY_HINTS: readonly ["low", "normal", "high", "urgent"];
17
+ export type SupportSeverityHint = (typeof SUPPORT_SEVERITY_HINTS)[number];
18
+ /**
19
+ * What the submitter says the request is about. Optional on intake (omitted
20
+ * means `"other"`); Work stores it apart from its own AI-assigned triage
21
+ * category and only ever returns one of these values.
22
+ */
23
+ export declare const SUPPORT_CATEGORIES: readonly ["bug", "feature_request", "question", "account", "other"];
24
+ export type SupportCategory = (typeof SUPPORT_CATEGORIES)[number];
25
+ export declare const SUPPORT_DEFAULT_CATEGORY: SupportCategory;
26
+ /** Narrows any stored or received value to a known category, coercing everything else to `"other"`. */
27
+ export declare function normalizeSupportCategory(value: unknown): SupportCategory;
28
+ /** Field limits enforced by Work. Submissions over a limit are rejected, never truncated. */
29
+ export declare const SUPPORT_LIMITS: {
30
+ /** Largest accepted request body, in bytes. */
31
+ readonly maxBodyBytes: number;
32
+ readonly submissionIdMax: 100;
33
+ readonly subjectMax: 160;
34
+ readonly descriptionMin: 10;
35
+ readonly descriptionMax: 8000;
36
+ readonly externalUserIdMax: 200;
37
+ readonly emailMax: 320;
38
+ readonly productFieldMax: 100;
39
+ readonly logExcerptMax: 16000;
40
+ /** Largest serialized (UTF-8 JSON) `product.diagnostics`, in bytes. */
41
+ readonly diagnosticsMaxBytes: number;
42
+ /** Deepest nesting of `product.diagnostics`; the object itself is depth 1. */
43
+ readonly diagnosticsMaxDepth: 6;
44
+ readonly pageSizeDefault: 50;
45
+ readonly pageSizeMax: 200;
46
+ /** Longest `externalUser.displayName`. */
47
+ readonly displayNameMax: 120;
48
+ /** Longest reply `messageId`. */
49
+ readonly messageIdMax: 100;
50
+ /** Longest reply `body` (characters); replies must also fit `maxBodyBytes`. */
51
+ readonly replyBodyMax: 8000;
52
+ /** Most cases one claim call moves; call again while the response says `more`. */
53
+ readonly claimMaxCases: 50;
54
+ /** Largest single attachment, in bytes. Also the upload route's request-body cap. */
55
+ readonly attachmentMaxBytes: number;
56
+ /** Most `attachmentIds` one submission or reply may reference. */
57
+ readonly attachmentIdsPerRequestMax: 5;
58
+ /** Most attachments a case may hold across its whole lifetime. */
59
+ readonly attachmentsPerCaseMax: 10;
60
+ /** Longest clip `transcribe` accepts, in seconds. */
61
+ readonly transcribeMaxSeconds: 60;
62
+ /** Largest `transcribe` request body, in bytes (also its pre-auth read cap). */
63
+ readonly transcribeMaxBytes: number;
64
+ /** Longest stored or returned transcript, in characters; longer text is cut. */
65
+ readonly transcriptMaxChars: 20000;
66
+ };
67
+ /**
68
+ * Media types Work accepts as attachments. Work sniffs the bytes, so the
69
+ * declared `Content-Type` is only checked for consistency, never trusted.
70
+ * `audio/mp4` and `audio/webm` are the ISO-BMFF and Matroska containers
71
+ * browsers record voice notes in; their tracks are not inspected.
72
+ */
73
+ export declare const SUPPORT_ATTACHMENT_MIME_TYPES: readonly ["image/png", "image/jpeg", "image/webp", "audio/webm", "audio/wav", "audio/ogg", "audio/mp4"];
74
+ export type SupportAttachmentMimeType = (typeof SUPPORT_ATTACHMENT_MIME_TYPES)[number];
75
+ export type SupportAttachmentKind = 'image' | 'audio';
76
+ export declare function supportAttachmentKind(mimeType: SupportAttachmentMimeType): SupportAttachmentKind;
77
+ /** Attachment ids are UUIDs minted by Work at upload. */
78
+ export declare function isSupportAttachmentId(value: unknown): value is string;
79
+ export declare function isSupportExternalUserId(value: unknown): value is string;
80
+ export interface SupportExternalUser {
81
+ /**
82
+ * The product's own account reference. Not a Work profile. Any string up to
83
+ * `SUPPORT_LIMITS.externalUserIdMax` without control characters, other than
84
+ * `.` or `..` (see `isSupportExternalUserId`).
85
+ */
86
+ id: string;
87
+ email?: string;
88
+ displayName?: string;
89
+ /**
90
+ * True for a guest/instant-play identity. Only submissions made by an
91
+ * anonymous user can later be claimed into an account. Never returned.
92
+ */
93
+ isAnonymous?: boolean;
94
+ }
95
+ export interface SupportProductMetadata {
96
+ version?: string;
97
+ platform?: string;
98
+ build?: string;
99
+ /** Bounded log excerpt; stays internal to Work and is never returned to clients. */
100
+ logExcerpt?: string;
101
+ /**
102
+ * Structured, machine-readable context captured when the issue occurred
103
+ * (build, OS/GPU, route, telemetry snapshots, repro flags). JSON-serializable,
104
+ * at most `SUPPORT_LIMITS.diagnosticsMaxBytes` serialized and
105
+ * `diagnosticsMaxDepth` deep. Stays internal to Work and the product-admin
106
+ * tier; never returned on submitter read-back.
107
+ */
108
+ diagnostics?: Record<string, unknown>;
109
+ }
110
+ export interface SupportUploadResponse {
111
+ ok: true;
112
+ /** Reference this from `attachmentIds` on a submission or reply. */
113
+ attachmentId: string;
114
+ kind: SupportAttachmentKind;
115
+ /** The type Work sniffed from the bytes. */
116
+ mimeType: SupportAttachmentMimeType;
117
+ bytes: number;
118
+ /** Lowercase-hex SHA-256 Work computed over the stored bytes. */
119
+ sha256: string;
120
+ /** An upload nothing has referenced by this time is deleted. */
121
+ expiresAt: string;
122
+ }
123
+ export interface SupportTranscribeResponse {
124
+ ok: true;
125
+ /** What was said, as text. Untrusted: render it as text, never as markup. */
126
+ transcript: string;
127
+ /** Language the speech-to-text model detected, when it reports one. */
128
+ language?: string;
129
+ /** Clip length in milliseconds as the speech model reported it, when it did. */
130
+ durationMs?: number;
131
+ }
132
+ /** Where an audio attachment's asynchronous transcription stands (product-admin tier). */
133
+ export type SupportTranscriptStatus = 'pending' | 'processing' | 'done' | 'failed';
134
+ export interface SupportAttachmentTranscript {
135
+ status: SupportTranscriptStatus;
136
+ /** Present only when `status` is `done`. */
137
+ text?: string;
138
+ language?: string;
139
+ durationMs?: number;
140
+ }
141
+ /**
142
+ * What a participant (the submitter) may see of an attachment: no digest, type
143
+ * or download route. A voice note's transcript is the participant's own words,
144
+ * so it is returned once it exists.
145
+ */
146
+ export interface SupportAttachmentSummary {
147
+ id: string;
148
+ kind: SupportAttachmentKind;
149
+ bytes: number;
150
+ /** The voice note's transcript, once transcribed. */
151
+ transcript?: string;
152
+ }
153
+ /** Product-admin tier descriptor; bytes come from the signed admin download route. */
154
+ export interface SupportAttachmentDescriptor {
155
+ id: string;
156
+ kind: SupportAttachmentKind;
157
+ mimeType: SupportAttachmentMimeType;
158
+ bytes: number;
159
+ sha256: string;
160
+ createdAt: string;
161
+ /** The timeline entry the attachment was sent with. */
162
+ interactionId: string | null;
163
+ /** Audio only. Absent for images and for audio that is not queued for transcription. */
164
+ transcript?: SupportAttachmentTranscript;
165
+ }
166
+ export interface SupportSubmitRequest {
167
+ /** Product-generated idempotency key; resubmitting the same id returns the same case. */
168
+ submissionId: string;
169
+ subject: string;
170
+ description: string;
171
+ severity?: SupportSeverityHint;
172
+ /** Request intent; defaults to `"other"` when omitted. */
173
+ category?: SupportCategory;
174
+ externalUser: SupportExternalUser;
175
+ product?: SupportProductMetadata;
176
+ /**
177
+ * Uploads (see `uploadAttachment`) to link to the case, at most
178
+ * `SUPPORT_LIMITS.attachmentIdsPerRequestMax`. An id that is unknown, from
179
+ * another product, expired or already linked elsewhere fails the whole
180
+ * request with one uniform 400; nothing is created.
181
+ */
182
+ attachmentIds?: string[];
183
+ }
184
+ /**
185
+ * Coarse, client-facing status. Work's finer lifecycle collapses to these so
186
+ * products never depend on internal triage states.
187
+ */
188
+ export declare const SUPPORT_CLIENT_STATUSES: readonly ["received", "in_progress", "waiting_on_you", "resolved", "closed"];
189
+ export type SupportClientStatus = (typeof SUPPORT_CLIENT_STATUSES)[number];
190
+ export interface SupportSubmitResponse {
191
+ ok: true;
192
+ caseNumber: string;
193
+ submissionId: string;
194
+ status: SupportClientStatus;
195
+ /** False when the submissionId was already known and the original case was returned. */
196
+ created: boolean;
197
+ }
198
+ export interface SupportClientTimelineEntry {
199
+ id: string;
200
+ /** `inbound` is what the submitter wrote; `outbound` is a reply from support. */
201
+ direction: 'inbound' | 'outbound';
202
+ body: string;
203
+ occurredAt: string;
204
+ /** Participant-safe metadata of what this message carried; omitted when none. */
205
+ attachments?: SupportAttachmentSummary[];
206
+ }
207
+ export interface SupportSubmissionView {
208
+ ok: true;
209
+ submissionId: string;
210
+ caseNumber: string;
211
+ subject: string;
212
+ category: SupportCategory;
213
+ status: SupportClientStatus;
214
+ openedAt: string;
215
+ lastActivityAt: string;
216
+ timeline: SupportClientTimelineEntry[];
217
+ }
218
+ export interface SupportReplyRequest {
219
+ /** Product-generated idempotency key for this message, unique within the submission. */
220
+ messageId: string;
221
+ /** Must be the user who owns the submission. */
222
+ externalUser: {
223
+ id: string;
224
+ };
225
+ body: string;
226
+ /** Uploads to link to this message; same rules as `SupportSubmitRequest.attachmentIds`. */
227
+ attachmentIds?: string[];
228
+ }
229
+ export interface SupportReplyResponse {
230
+ ok: true;
231
+ submissionId: string;
232
+ messageId: string;
233
+ /** The timeline entry id of the recorded message. */
234
+ interactionId: string;
235
+ status: SupportClientStatus;
236
+ /** False when the messageId was already recorded and the original is returned. */
237
+ created: boolean;
238
+ }
239
+ /** One row of a user's submission list. Client-safe fields only. */
240
+ export interface SupportUserSubmissionSummary {
241
+ submissionId: string;
242
+ caseNumber: string;
243
+ subject: string;
244
+ category: SupportCategory;
245
+ status: SupportClientStatus;
246
+ openedAt: string;
247
+ /** Latest participant-visible message (yours or support's); never internal activity. */
248
+ lastActivityAt: string;
249
+ /** Latest message from support, or null when support has not replied. */
250
+ lastOutboundAt: string | null;
251
+ }
252
+ export interface SupportUserSubmissionsQuery {
253
+ /** Page size, 1..`SUPPORT_LIMITS.pageSizeMax`. */
254
+ limit?: number;
255
+ /** Opaque cursor from a previous page's `nextCursor`. */
256
+ cursor?: string;
257
+ /** ISO timestamp; only submissions with visible activity strictly after it. */
258
+ since?: string;
259
+ }
260
+ export interface SupportUserSubmissionsResponse {
261
+ ok: true;
262
+ submissions: SupportUserSubmissionSummary[];
263
+ nextCursor: string | null;
264
+ /** Use as `since` on the next poll; slightly behind the server clock so no activity is missed. */
265
+ serverTime: string;
266
+ }
267
+ export interface SupportClaimRequest {
268
+ /** The anonymous identity whose submissions move. */
269
+ fromExternalUserId: string;
270
+ /** The account that takes them over. */
271
+ toExternalUser: {
272
+ id: string;
273
+ displayName?: string;
274
+ email?: string;
275
+ };
276
+ }
277
+ export interface SupportClaimResponse {
278
+ ok: true;
279
+ /** Submissions moved by this call; 0 when nothing was left to claim. */
280
+ claimed: number;
281
+ /** True when more than `SUPPORT_LIMITS.claimMaxCases` were found: call again. */
282
+ more: boolean;
283
+ }
284
+ export interface SupportAdminCaseSummary {
285
+ caseNumber: string;
286
+ subject: string;
287
+ /** The product-declared category (`"other"` when none was given). */
288
+ category: SupportCategory;
289
+ /** Work's case lifecycle status (e.g. `new`, `triaged`, `in_progress`, `resolved`). */
290
+ status: string;
291
+ severity: string | null;
292
+ priority: string | null;
293
+ openedAt: string | null;
294
+ lastActivityAt: string | null;
295
+ /** The product's submissionId, when the case came from this API. */
296
+ submissionId: string | null;
297
+ }
298
+ export interface SupportAdminListQuery {
299
+ /** Page size, 1..`SUPPORT_LIMITS.pageSizeMax`. */
300
+ limit?: number;
301
+ /** Opaque cursor from a previous page's `nextCursor`. */
302
+ cursor?: string;
303
+ /** ISO timestamp; only cases with activity strictly after it are returned. */
304
+ since?: string;
305
+ }
306
+ export interface SupportAdminListResponse {
307
+ ok: true;
308
+ cases: SupportAdminCaseSummary[];
309
+ /** Pass as `cursor` for the next page; null when exhausted. */
310
+ nextCursor: string | null;
311
+ /** Use as `since` on the next poll to receive only newer activity. */
312
+ serverTime: string;
313
+ }
314
+ /** Product-supplied context returned only on the product-admin case detail. */
315
+ export interface SupportAdminProductContext {
316
+ version?: string;
317
+ platform?: string;
318
+ build?: string;
319
+ logExcerpt?: string;
320
+ diagnostics?: Record<string, unknown>;
321
+ }
322
+ export interface SupportAdminCaseResponse {
323
+ ok: true;
324
+ case: SupportAdminCaseSummary;
325
+ /** Present when the product supplied metadata at intake. */
326
+ product?: SupportAdminProductContext;
327
+ timeline: SupportClientTimelineEntry[];
328
+ /** Every attachment on the case; download through `downloadAttachment`. */
329
+ attachments: SupportAttachmentDescriptor[];
330
+ }
331
+ export interface SupportApiErrorBody {
332
+ ok: false;
333
+ error: string;
334
+ }
335
+ /**
336
+ * Structural twin of smrt-support's `SupportCaseView` (what `CaseQueue` /
337
+ * `CaseDetail` render), declared here so products need no Work or smrt
338
+ * dependency to adapt an admin summary into it.
339
+ */
340
+ export interface SupportCaseViewLike {
341
+ id: string;
342
+ caseNumber: string;
343
+ subject: string;
344
+ category: SupportCategory;
345
+ status: string;
346
+ priority: string;
347
+ severity: string;
348
+ channelKind: string;
349
+ clientProfileId: string | null;
350
+ projectId: string | null;
351
+ assignedSpecialistId: string | null;
352
+ assignedSpecialistName: string | null;
353
+ reopenCount: number;
354
+ createdAt: string | null;
355
+ updatedAt: string | null;
356
+ resolutionSummary: string;
357
+ }
358
+ /** Adapts an admin-list row to the `SupportCaseView` that smrt-support's Svelte components take. */
359
+ export declare function adminSummaryToCaseView(summary: SupportAdminCaseSummary): SupportCaseViewLike;
360
+ /** Structural twin of smrt-support's `CaseTimelineItemView`, for `CaseDetail`'s timeline. */
361
+ export interface SupportTimelineItemViewLike {
362
+ kind: 'interaction' | 'event';
363
+ occurredAt: string;
364
+ actorKind: string;
365
+ summary: string;
366
+ body: string;
367
+ direction: string | null;
368
+ channelKind: string | null;
369
+ eventType: string | null;
370
+ }
371
+ export declare function timelineEntryToItemView(entry: SupportClientTimelineEntry): SupportTimelineItemViewLike;
372
+ /**
373
+ * Validates `product.diagnostics` against the contract bounds. Returns a
374
+ * human-readable problem, or `null` when the value is acceptable. Shared by
375
+ * Work's intake and by products that want to check before sending.
376
+ */
377
+ export declare function validateSupportDiagnostics(value: unknown): string | null;
378
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,eAAO,MAAM,qBAAqB,iCAAiC,CAAC;AAEpE,eAAO,MAAM,sBAAsB,yBAAyB,CAAC;AAC7D,eAAO,MAAM,wBAAwB,2BAA2B,CAAC;AACjE,eAAO,MAAM,wBAAwB,2BAA2B,CAAC;AACjE;;;;GAIG;AACH,eAAO,MAAM,6BAA6B,gCAAgC,CAAC;AAE3E,eAAO,MAAM,sBAAsB,8CAKzB,CAAC;AACX,MAAM,MAAM,mBAAmB,GAAG,CAAC,OAAO,sBAAsB,CAAC,CAAC,MAAM,CAAC,CAAC;AAE1E;;;;GAIG;AACH,eAAO,MAAM,kBAAkB,qEAMrB,CAAC;AACX,MAAM,MAAM,eAAe,GAAG,CAAC,OAAO,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC;AAElE,eAAO,MAAM,wBAAwB,EAAE,eAAyB,CAAC;AAEjE,uGAAuG;AACvG,wBAAgB,wBAAwB,CAAC,KAAK,EAAE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,OAAO,EAAE,uBAAuB,GAC/B,mBAAmB,CAmBrB;AAED,6FAA6F;AAC7F,MAAM,WAAW,2BAA2B;IAC1C,IAAI,EAAE,aAAa,GAAG,OAAO,CAAC;IAC9B,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;CAC1B;AAED,wBAAgB,uBAAuB,CACrC,KAAK,EAAE,0BAA0B,GAChC,2BAA2B,CAW7B;AAED;;;;GAIG;AACH,wBAAgB,0BAA0B,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,IAAI,CAqBxE"}
package/dist/types.js ADDED
@@ -0,0 +1,143 @@
1
+ //#region src/types.ts
2
+ var SUPPORT_API_BASE_PATH = "/api/public/support-requests";
3
+ var SUPPORT_PRODUCT_HEADER = "x-hv-support-product";
4
+ var SUPPORT_TIMESTAMP_HEADER = "x-hv-support-timestamp";
5
+ var SUPPORT_SIGNATURE_HEADER = "x-hv-support-signature";
6
+ var SUPPORT_CONTENT_SHA256_HEADER = "x-hv-support-content-sha256";
7
+ var SUPPORT_SEVERITY_HINTS = [
8
+ "low",
9
+ "normal",
10
+ "high",
11
+ "urgent"
12
+ ];
13
+ var SUPPORT_CATEGORIES = [
14
+ "bug",
15
+ "feature_request",
16
+ "question",
17
+ "account",
18
+ "other"
19
+ ];
20
+ var SUPPORT_DEFAULT_CATEGORY = "other";
21
+ function normalizeSupportCategory(value) {
22
+ return typeof value === "string" && SUPPORT_CATEGORIES.includes(value) ? value : SUPPORT_DEFAULT_CATEGORY;
23
+ }
24
+ var SUPPORT_LIMITS = {
25
+ /** Largest accepted request body, in bytes. */
26
+ maxBodyBytes: 96 * 1024,
27
+ submissionIdMax: 100,
28
+ subjectMax: 160,
29
+ descriptionMin: 10,
30
+ descriptionMax: 8e3,
31
+ externalUserIdMax: 200,
32
+ emailMax: 320,
33
+ productFieldMax: 100,
34
+ logExcerptMax: 16e3,
35
+ /** Largest serialized (UTF-8 JSON) `product.diagnostics`, in bytes. */
36
+ diagnosticsMaxBytes: 16 * 1024,
37
+ /** Deepest nesting of `product.diagnostics`; the object itself is depth 1. */
38
+ diagnosticsMaxDepth: 6,
39
+ pageSizeDefault: 50,
40
+ pageSizeMax: 200,
41
+ /** Longest `externalUser.displayName`. */
42
+ displayNameMax: 120,
43
+ /** Longest reply `messageId`. */
44
+ messageIdMax: 100,
45
+ /** Longest reply `body` (characters); replies must also fit `maxBodyBytes`. */
46
+ replyBodyMax: 8e3,
47
+ /** Most cases one claim call moves; call again while the response says `more`. */
48
+ claimMaxCases: 50,
49
+ /** Largest single attachment, in bytes. Also the upload route's request-body cap. */
50
+ attachmentMaxBytes: 8 * 1024 * 1024,
51
+ /** Most `attachmentIds` one submission or reply may reference. */
52
+ attachmentIdsPerRequestMax: 5,
53
+ /** Most attachments a case may hold across its whole lifetime. */
54
+ attachmentsPerCaseMax: 10,
55
+ /** Longest clip `transcribe` accepts, in seconds. */
56
+ transcribeMaxSeconds: 60,
57
+ /** Largest `transcribe` request body, in bytes (also its pre-auth read cap). */
58
+ transcribeMaxBytes: 4 * 1024 * 1024,
59
+ /** Longest stored or returned transcript, in characters; longer text is cut. */
60
+ transcriptMaxChars: 2e4
61
+ };
62
+ var SUPPORT_ATTACHMENT_MIME_TYPES = [
63
+ "image/png",
64
+ "image/jpeg",
65
+ "image/webp",
66
+ "audio/webm",
67
+ "audio/wav",
68
+ "audio/ogg",
69
+ "audio/mp4"
70
+ ];
71
+ function supportAttachmentKind(mimeType) {
72
+ return mimeType.startsWith("image/") ? "image" : "audio";
73
+ }
74
+ var ATTACHMENT_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
75
+ function isSupportAttachmentId(value) {
76
+ return typeof value === "string" && ATTACHMENT_ID_PATTERN.test(value);
77
+ }
78
+ var CONTROL_CHARS = /\p{Cc}/u;
79
+ var LONE_SURROGATE = /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/;
80
+ function isSupportExternalUserId(value) {
81
+ return typeof value === "string" && value.length >= 1 && value.length <= SUPPORT_LIMITS.externalUserIdMax && value !== "." && value !== ".." && !CONTROL_CHARS.test(value) && !LONE_SURROGATE.test(value);
82
+ }
83
+ var SUPPORT_CLIENT_STATUSES = [
84
+ "received",
85
+ "in_progress",
86
+ "waiting_on_you",
87
+ "resolved",
88
+ "closed"
89
+ ];
90
+ function adminSummaryToCaseView(summary) {
91
+ return {
92
+ id: summary.caseNumber,
93
+ caseNumber: summary.caseNumber,
94
+ subject: summary.subject,
95
+ category: normalizeSupportCategory(summary.category),
96
+ status: summary.status,
97
+ priority: summary.priority ?? "normal",
98
+ severity: summary.severity ?? "",
99
+ channelKind: "api",
100
+ clientProfileId: null,
101
+ projectId: null,
102
+ assignedSpecialistId: null,
103
+ assignedSpecialistName: null,
104
+ reopenCount: 0,
105
+ createdAt: summary.openedAt,
106
+ updatedAt: summary.lastActivityAt,
107
+ resolutionSummary: ""
108
+ };
109
+ }
110
+ function timelineEntryToItemView(entry) {
111
+ return {
112
+ kind: "interaction",
113
+ occurredAt: entry.occurredAt,
114
+ actorKind: entry.direction === "inbound" ? "client" : "specialist",
115
+ summary: `${entry.direction} api`,
116
+ body: entry.body,
117
+ direction: entry.direction,
118
+ channelKind: "api",
119
+ eventType: null
120
+ };
121
+ }
122
+ function validateSupportDiagnostics(value) {
123
+ if (!value || typeof value !== "object" || Array.isArray(value)) return "must be an object";
124
+ if (!withinDepth(value, 1)) return `is nested deeper than ${SUPPORT_LIMITS.diagnosticsMaxDepth} levels`;
125
+ let serialized;
126
+ try {
127
+ serialized = JSON.stringify(value);
128
+ } catch {
129
+ return "is not JSON-serializable";
130
+ }
131
+ if (serialized === void 0) return "is not JSON-serializable";
132
+ if (new TextEncoder().encode(serialized).byteLength > SUPPORT_LIMITS.diagnosticsMaxBytes) return `exceeds ${SUPPORT_LIMITS.diagnosticsMaxBytes} bytes`;
133
+ return null;
134
+ }
135
+ function withinDepth(value, depth) {
136
+ if (!value || typeof value !== "object") return true;
137
+ if (depth > SUPPORT_LIMITS.diagnosticsMaxDepth) return false;
138
+ return (Array.isArray(value) ? value : Object.values(value)).every((child) => withinDepth(child, depth + 1));
139
+ }
140
+ //#endregion
141
+ export { SUPPORT_API_BASE_PATH, SUPPORT_ATTACHMENT_MIME_TYPES, SUPPORT_CATEGORIES, SUPPORT_CLIENT_STATUSES, SUPPORT_CONTENT_SHA256_HEADER, SUPPORT_DEFAULT_CATEGORY, SUPPORT_LIMITS, SUPPORT_PRODUCT_HEADER, SUPPORT_SEVERITY_HINTS, SUPPORT_SIGNATURE_HEADER, SUPPORT_TIMESTAMP_HEADER, adminSummaryToCaseView, isSupportAttachmentId, isSupportExternalUserId, normalizeSupportCategory, supportAttachmentKind, timelineEntryToItemView, validateSupportDiagnostics };
142
+
143
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","names":[],"sources":["../src/types.ts"],"sourcesContent":["/**\n * Wire contract for HappyVertical Work's product support API. Every shape here\n * is product-visible: Work never serialises tenant ids, profile ids, internal\n * events, AI-run internals or compensation data through these DTOs.\n */\n\nexport const SUPPORT_API_BASE_PATH = '/api/public/support-requests';\n\nexport const SUPPORT_PRODUCT_HEADER = 'x-hv-support-product';\nexport const SUPPORT_TIMESTAMP_HEADER = 'x-hv-support-timestamp';\nexport const SUPPORT_SIGNATURE_HEADER = 'x-hv-support-signature';\n/**\n * Optional lowercase-hex SHA-256 of an upload's bytes. When sent, Work\n * recomputes the digest and rejects a mismatch (422); it is an integrity\n * check on top of the HMAC, which already covers the body.\n */\nexport const SUPPORT_CONTENT_SHA256_HEADER = 'x-hv-support-content-sha256';\n\nexport const SUPPORT_SEVERITY_HINTS = [\n 'low',\n 'normal',\n 'high',\n 'urgent',\n] as const;\nexport type SupportSeverityHint = (typeof SUPPORT_SEVERITY_HINTS)[number];\n\n/**\n * What the submitter says the request is about. Optional on intake (omitted\n * means `\"other\"`); Work stores it apart from its own AI-assigned triage\n * category and only ever returns one of these values.\n */\nexport const SUPPORT_CATEGORIES = [\n 'bug',\n 'feature_request',\n 'question',\n 'account',\n 'other',\n] as const;\nexport type SupportCategory = (typeof SUPPORT_CATEGORIES)[number];\n\nexport const SUPPORT_DEFAULT_CATEGORY: SupportCategory = 'other';\n\n/** Narrows any stored or received value to a known category, coercing everything else to `\"other\"`. */\nexport function normalizeSupportCategory(value: unknown): SupportCategory {\n return typeof value === 'string' &&\n (SUPPORT_CATEGORIES as readonly string[]).includes(value)\n ? (value as SupportCategory)\n : SUPPORT_DEFAULT_CATEGORY;\n}\n\n/** Field limits enforced by Work. Submissions over a limit are rejected, never truncated. */\nexport const SUPPORT_LIMITS = {\n /** Largest accepted request body, in bytes. */\n maxBodyBytes: 96 * 1024,\n submissionIdMax: 100,\n subjectMax: 160,\n descriptionMin: 10,\n descriptionMax: 8_000,\n externalUserIdMax: 200,\n emailMax: 320,\n productFieldMax: 100,\n logExcerptMax: 16_000,\n /** Largest serialized (UTF-8 JSON) `product.diagnostics`, in bytes. */\n diagnosticsMaxBytes: 16 * 1024,\n /** Deepest nesting of `product.diagnostics`; the object itself is depth 1. */\n diagnosticsMaxDepth: 6,\n pageSizeDefault: 50,\n pageSizeMax: 200,\n /** Longest `externalUser.displayName`. */\n displayNameMax: 120,\n /** Longest reply `messageId`. */\n messageIdMax: 100,\n /** Longest reply `body` (characters); replies must also fit `maxBodyBytes`. */\n replyBodyMax: 8_000,\n /** Most cases one claim call moves; call again while the response says `more`. */\n claimMaxCases: 50,\n /** Largest single attachment, in bytes. Also the upload route's request-body cap. */\n attachmentMaxBytes: 8 * 1024 * 1024,\n /** Most `attachmentIds` one submission or reply may reference. */\n attachmentIdsPerRequestMax: 5,\n /** Most attachments a case may hold across its whole lifetime. */\n attachmentsPerCaseMax: 10,\n /** Longest clip `transcribe` accepts, in seconds. */\n transcribeMaxSeconds: 60,\n /** Largest `transcribe` request body, in bytes (also its pre-auth read cap). */\n transcribeMaxBytes: 4 * 1024 * 1024,\n /** Longest stored or returned transcript, in characters; longer text is cut. */\n transcriptMaxChars: 20_000,\n} as const;\n\n/**\n * Media types Work accepts as attachments. Work sniffs the bytes, so the\n * declared `Content-Type` is only checked for consistency, never trusted.\n * `audio/mp4` and `audio/webm` are the ISO-BMFF and Matroska containers\n * browsers record voice notes in; their tracks are not inspected.\n */\nexport const SUPPORT_ATTACHMENT_MIME_TYPES = [\n 'image/png',\n 'image/jpeg',\n 'image/webp',\n 'audio/webm',\n 'audio/wav',\n 'audio/ogg',\n 'audio/mp4',\n] as const;\nexport type SupportAttachmentMimeType =\n (typeof SUPPORT_ATTACHMENT_MIME_TYPES)[number];\n\nexport type SupportAttachmentKind = 'image' | 'audio';\n\nexport function supportAttachmentKind(\n mimeType: SupportAttachmentMimeType,\n): SupportAttachmentKind {\n return mimeType.startsWith('image/') ? 'image' : 'audio';\n}\n\nconst ATTACHMENT_ID_PATTERN =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/** Attachment ids are UUIDs minted by Work at upload. */\nexport function isSupportAttachmentId(value: unknown): value is string {\n return typeof value === 'string' && ATTACHMENT_ID_PATTERN.test(value);\n}\n\n/**\n * `externalUser.id` is the product's own account reference. 0.1.0 callers could\n * send any string up to the limit, so 0.2.0 stays permissive: any well-formed\n * Unicode string of 1..`SUPPORT_LIMITS.externalUserIdMax` UTF-16 units with no\n * control characters (`\\p{Cc}`), and not `.` or `..` (URL normalisation would\n * collapse those path segments). Everything else (`|`, spaces, `/`, `#`, `%`,\n * non-ASCII) is safe because the contract client sends the id through\n * `encodeURIComponent` and the server decodes the route parameter.\n */\nconst CONTROL_CHARS = /\\p{Cc}/u;\nconst LONE_SURROGATE =\n /[\\ud800-\\udbff](?![\\udc00-\\udfff])|(?<![\\ud800-\\udbff])[\\udc00-\\udfff]/;\n\nexport function isSupportExternalUserId(value: unknown): value is string {\n return (\n typeof value === 'string' &&\n value.length >= 1 &&\n value.length <= SUPPORT_LIMITS.externalUserIdMax &&\n value !== '.' &&\n value !== '..' &&\n !CONTROL_CHARS.test(value) &&\n !LONE_SURROGATE.test(value)\n );\n}\n\nexport interface SupportExternalUser {\n /**\n * The product's own account reference. Not a Work profile. Any string up to\n * `SUPPORT_LIMITS.externalUserIdMax` without control characters, other than\n * `.` or `..` (see `isSupportExternalUserId`).\n */\n id: string;\n email?: string;\n displayName?: string;\n /**\n * True for a guest/instant-play identity. Only submissions made by an\n * anonymous user can later be claimed into an account. Never returned.\n */\n isAnonymous?: boolean;\n}\n\nexport interface SupportProductMetadata {\n version?: string;\n platform?: string;\n build?: string;\n /** Bounded log excerpt; stays internal to Work and is never returned to clients. */\n logExcerpt?: string;\n /**\n * Structured, machine-readable context captured when the issue occurred\n * (build, OS/GPU, route, telemetry snapshots, repro flags). JSON-serializable,\n * at most `SUPPORT_LIMITS.diagnosticsMaxBytes` serialized and\n * `diagnosticsMaxDepth` deep. Stays internal to Work and the product-admin\n * tier; never returned on submitter read-back.\n */\n diagnostics?: Record<string, unknown>;\n}\n\nexport interface SupportUploadResponse {\n ok: true;\n /** Reference this from `attachmentIds` on a submission or reply. */\n attachmentId: string;\n kind: SupportAttachmentKind;\n /** The type Work sniffed from the bytes. */\n mimeType: SupportAttachmentMimeType;\n bytes: number;\n /** Lowercase-hex SHA-256 Work computed over the stored bytes. */\n sha256: string;\n /** An upload nothing has referenced by this time is deleted. */\n expiresAt: string;\n}\n\nexport interface SupportTranscribeResponse {\n ok: true;\n /** What was said, as text. Untrusted: render it as text, never as markup. */\n transcript: string;\n /** Language the speech-to-text model detected, when it reports one. */\n language?: string;\n /** Clip length in milliseconds as the speech model reported it, when it did. */\n durationMs?: number;\n}\n\n/** Where an audio attachment's asynchronous transcription stands (product-admin tier). */\nexport type SupportTranscriptStatus =\n | 'pending'\n | 'processing'\n | 'done'\n | 'failed';\n\nexport interface SupportAttachmentTranscript {\n status: SupportTranscriptStatus;\n /** Present only when `status` is `done`. */\n text?: string;\n language?: string;\n durationMs?: number;\n}\n\n/**\n * What a participant (the submitter) may see of an attachment: no digest, type\n * or download route. A voice note's transcript is the participant's own words,\n * so it is returned once it exists.\n */\nexport interface SupportAttachmentSummary {\n id: string;\n kind: SupportAttachmentKind;\n bytes: number;\n /** The voice note's transcript, once transcribed. */\n transcript?: string;\n}\n\n/** Product-admin tier descriptor; bytes come from the signed admin download route. */\nexport interface SupportAttachmentDescriptor {\n id: string;\n kind: SupportAttachmentKind;\n mimeType: SupportAttachmentMimeType;\n bytes: number;\n sha256: string;\n createdAt: string;\n /** The timeline entry the attachment was sent with. */\n interactionId: string | null;\n /** Audio only. Absent for images and for audio that is not queued for transcription. */\n transcript?: SupportAttachmentTranscript;\n}\n\nexport interface SupportSubmitRequest {\n /** Product-generated idempotency key; resubmitting the same id returns the same case. */\n submissionId: string;\n subject: string;\n description: string;\n severity?: SupportSeverityHint;\n /** Request intent; defaults to `\"other\"` when omitted. */\n category?: SupportCategory;\n externalUser: SupportExternalUser;\n product?: SupportProductMetadata;\n /**\n * Uploads (see `uploadAttachment`) to link to the case, at most\n * `SUPPORT_LIMITS.attachmentIdsPerRequestMax`. An id that is unknown, from\n * another product, expired or already linked elsewhere fails the whole\n * request with one uniform 400; nothing is created.\n */\n attachmentIds?: string[];\n}\n\n/**\n * Coarse, client-facing status. Work's finer lifecycle collapses to these so\n * products never depend on internal triage states.\n */\nexport const SUPPORT_CLIENT_STATUSES = [\n 'received',\n 'in_progress',\n 'waiting_on_you',\n 'resolved',\n 'closed',\n] as const;\nexport type SupportClientStatus = (typeof SUPPORT_CLIENT_STATUSES)[number];\n\nexport interface SupportSubmitResponse {\n ok: true;\n caseNumber: string;\n submissionId: string;\n status: SupportClientStatus;\n /** False when the submissionId was already known and the original case was returned. */\n created: boolean;\n}\n\nexport interface SupportClientTimelineEntry {\n id: string;\n /** `inbound` is what the submitter wrote; `outbound` is a reply from support. */\n direction: 'inbound' | 'outbound';\n body: string;\n occurredAt: string;\n /** Participant-safe metadata of what this message carried; omitted when none. */\n attachments?: SupportAttachmentSummary[];\n}\n\nexport interface SupportSubmissionView {\n ok: true;\n submissionId: string;\n caseNumber: string;\n subject: string;\n category: SupportCategory;\n status: SupportClientStatus;\n openedAt: string;\n lastActivityAt: string;\n timeline: SupportClientTimelineEntry[];\n}\n\nexport interface SupportReplyRequest {\n /** Product-generated idempotency key for this message, unique within the submission. */\n messageId: string;\n /** Must be the user who owns the submission. */\n externalUser: { id: string };\n body: string;\n /** Uploads to link to this message; same rules as `SupportSubmitRequest.attachmentIds`. */\n attachmentIds?: string[];\n}\n\nexport interface SupportReplyResponse {\n ok: true;\n submissionId: string;\n messageId: string;\n /** The timeline entry id of the recorded message. */\n interactionId: string;\n status: SupportClientStatus;\n /** False when the messageId was already recorded and the original is returned. */\n created: boolean;\n}\n\n/** One row of a user's submission list. Client-safe fields only. */\nexport interface SupportUserSubmissionSummary {\n submissionId: string;\n caseNumber: string;\n subject: string;\n category: SupportCategory;\n status: SupportClientStatus;\n openedAt: string;\n /** Latest participant-visible message (yours or support's); never internal activity. */\n lastActivityAt: string;\n /** Latest message from support, or null when support has not replied. */\n lastOutboundAt: string | null;\n}\n\nexport interface SupportUserSubmissionsQuery {\n /** Page size, 1..`SUPPORT_LIMITS.pageSizeMax`. */\n limit?: number;\n /** Opaque cursor from a previous page's `nextCursor`. */\n cursor?: string;\n /** ISO timestamp; only submissions with visible activity strictly after it. */\n since?: string;\n}\n\nexport interface SupportUserSubmissionsResponse {\n ok: true;\n submissions: SupportUserSubmissionSummary[];\n nextCursor: string | null;\n /** Use as `since` on the next poll; slightly behind the server clock so no activity is missed. */\n serverTime: string;\n}\n\nexport interface SupportClaimRequest {\n /** The anonymous identity whose submissions move. */\n fromExternalUserId: string;\n /** The account that takes them over. */\n toExternalUser: { id: string; displayName?: string; email?: string };\n}\n\nexport interface SupportClaimResponse {\n ok: true;\n /** Submissions moved by this call; 0 when nothing was left to claim. */\n claimed: number;\n /** True when more than `SUPPORT_LIMITS.claimMaxCases` were found: call again. */\n more: boolean;\n}\n\nexport interface SupportAdminCaseSummary {\n caseNumber: string;\n subject: string;\n /** The product-declared category (`\"other\"` when none was given). */\n category: SupportCategory;\n /** Work's case lifecycle status (e.g. `new`, `triaged`, `in_progress`, `resolved`). */\n status: string;\n severity: string | null;\n priority: string | null;\n openedAt: string | null;\n lastActivityAt: string | null;\n /** The product's submissionId, when the case came from this API. */\n submissionId: string | null;\n}\n\nexport interface SupportAdminListQuery {\n /** Page size, 1..`SUPPORT_LIMITS.pageSizeMax`. */\n limit?: number;\n /** Opaque cursor from a previous page's `nextCursor`. */\n cursor?: string;\n /** ISO timestamp; only cases with activity strictly after it are returned. */\n since?: string;\n}\n\nexport interface SupportAdminListResponse {\n ok: true;\n cases: SupportAdminCaseSummary[];\n /** Pass as `cursor` for the next page; null when exhausted. */\n nextCursor: string | null;\n /** Use as `since` on the next poll to receive only newer activity. */\n serverTime: string;\n}\n\n/** Product-supplied context returned only on the product-admin case detail. */\nexport interface SupportAdminProductContext {\n version?: string;\n platform?: string;\n build?: string;\n logExcerpt?: string;\n diagnostics?: Record<string, unknown>;\n}\n\nexport interface SupportAdminCaseResponse {\n ok: true;\n case: SupportAdminCaseSummary;\n /** Present when the product supplied metadata at intake. */\n product?: SupportAdminProductContext;\n timeline: SupportClientTimelineEntry[];\n /** Every attachment on the case; download through `downloadAttachment`. */\n attachments: SupportAttachmentDescriptor[];\n}\n\nexport interface SupportApiErrorBody {\n ok: false;\n error: string;\n}\n\n/**\n * Structural twin of smrt-support's `SupportCaseView` (what `CaseQueue` /\n * `CaseDetail` render), declared here so products need no Work or smrt\n * dependency to adapt an admin summary into it.\n */\nexport interface SupportCaseViewLike {\n id: string;\n caseNumber: string;\n subject: string;\n category: SupportCategory;\n status: string;\n priority: string;\n severity: string;\n channelKind: string;\n clientProfileId: string | null;\n projectId: string | null;\n assignedSpecialistId: string | null;\n assignedSpecialistName: string | null;\n reopenCount: number;\n createdAt: string | null;\n updatedAt: string | null;\n resolutionSummary: string;\n}\n\n/** Adapts an admin-list row to the `SupportCaseView` that smrt-support's Svelte components take. */\nexport function adminSummaryToCaseView(\n summary: SupportAdminCaseSummary,\n): SupportCaseViewLike {\n return {\n id: summary.caseNumber,\n caseNumber: summary.caseNumber,\n subject: summary.subject,\n category: normalizeSupportCategory(summary.category),\n status: summary.status,\n priority: summary.priority ?? 'normal',\n severity: summary.severity ?? '',\n channelKind: 'api',\n clientProfileId: null,\n projectId: null,\n assignedSpecialistId: null,\n assignedSpecialistName: null,\n reopenCount: 0,\n createdAt: summary.openedAt,\n updatedAt: summary.lastActivityAt,\n resolutionSummary: '',\n };\n}\n\n/** Structural twin of smrt-support's `CaseTimelineItemView`, for `CaseDetail`'s timeline. */\nexport interface SupportTimelineItemViewLike {\n kind: 'interaction' | 'event';\n occurredAt: string;\n actorKind: string;\n summary: string;\n body: string;\n direction: string | null;\n channelKind: string | null;\n eventType: string | null;\n}\n\nexport function timelineEntryToItemView(\n entry: SupportClientTimelineEntry,\n): SupportTimelineItemViewLike {\n return {\n kind: 'interaction',\n occurredAt: entry.occurredAt,\n actorKind: entry.direction === 'inbound' ? 'client' : 'specialist',\n summary: `${entry.direction} api`,\n body: entry.body,\n direction: entry.direction,\n channelKind: 'api',\n eventType: null,\n };\n}\n\n/**\n * Validates `product.diagnostics` against the contract bounds. Returns a\n * human-readable problem, or `null` when the value is acceptable. Shared by\n * Work's intake and by products that want to check before sending.\n */\nexport function validateSupportDiagnostics(value: unknown): string | null {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return 'must be an object';\n }\n if (!withinDepth(value, 1)) {\n return `is nested deeper than ${SUPPORT_LIMITS.diagnosticsMaxDepth} levels`;\n }\n let serialized: string | undefined;\n try {\n serialized = JSON.stringify(value);\n } catch {\n return 'is not JSON-serializable';\n }\n if (serialized === undefined) return 'is not JSON-serializable';\n if (\n new TextEncoder().encode(serialized).byteLength >\n SUPPORT_LIMITS.diagnosticsMaxBytes\n ) {\n return `exceeds ${SUPPORT_LIMITS.diagnosticsMaxBytes} bytes`;\n }\n return null;\n}\n\nfunction withinDepth(value: unknown, depth: number): boolean {\n if (!value || typeof value !== 'object') return true;\n if (depth > SUPPORT_LIMITS.diagnosticsMaxDepth) return false;\n const children = Array.isArray(value) ? value : Object.values(value);\n return children.every((child) => withinDepth(child, depth + 1));\n}\n"],"mappings":";AAMO,IAAM,wBAAwB;AAE9B,IAAM,yBAAyB;AAC/B,IAAM,2BAA2B;AACjC,IAAM,2BAA2B;AAMjC,IAAM,gCAAgC;AAEtC,IAAM,yBAAyB;CACpC;CACA;CACA;CACA;AACF;AAQO,IAAM,qBAAqB;CAChC;CACA;CACA;CACA;CACA;AACF;AAGO,IAAM,2BAA4C;AAGlD,SAAS,yBAAyB,OAAiC;CACxE,OAAO,OAAO,UAAU,YACrB,mBAAyC,SAAS,KAAK,IACrD,QACD;AACN;AAGO,IAAM,iBAAiB;;CAE5B,cAAc,KAAK;CACnB,iBAAiB;CACjB,YAAY;CACZ,gBAAgB;CAChB,gBAAgB;CAChB,mBAAmB;CACnB,UAAU;CACV,iBAAiB;CACjB,eAAe;;CAEf,qBAAqB,KAAK;;CAE1B,qBAAqB;CACrB,iBAAiB;CACjB,aAAa;;CAEb,gBAAgB;;CAEhB,cAAc;;CAEd,cAAc;;CAEd,eAAe;;CAEf,oBAAoB,IAAI,OAAO;;CAE/B,4BAA4B;;CAE5B,uBAAuB;;CAEvB,sBAAsB;;CAEtB,oBAAoB,IAAI,OAAO;;CAE/B,oBAAoB;AACtB;AAQO,IAAM,gCAAgC;CAC3C;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAMO,SA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OAAO;CACT;CACA,IAAI,eAAe,KAAA,GAAW,OAAO;CACrC,IACE,IAAI,YAAY,CAAA,CAAE,OAAO,UAAU,CAAA,CAAE,aACrC,eAAe,qBAEf,OAAO,WAAW,eAAe,oBAAmB;CAEtD,OAAO;AACT;AAEA,SAAS,YAAY,OAAgB,OAAwB;CAC3D,IAAI,CAAC,SAAS,OAAO,UAAU,UAAU,OAAO;CAChD,IAAI,QAAQ,eAAe,qBAAqB,OAAO;CAEvD,QADiB,MAAM,QAAQ,KAAK,IAAI,QAAQ,OAAO,OAAO,KAAK,EAAA,CACnD,OAAO,UAAU,YAAY,OAAO,QAAQ,CAAC,CAAC;AAChE"}
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
2
  "name": "@happyvertical/smrt-support-contract",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.74.5",
4
+ "description": "Public wire contract, request signing and fetch client for HappyVertical Work's signed product support intake API",
5
+ "author": "HappyVertical",
6
+ "license": "MIT",
7
+ "type": "module",
8
+ "main": "dist/index.js",
9
+ "types": "dist/index.d.ts",
10
+ "files": [
11
+ "CLAUDE.md",
12
+ "dist",
13
+ "AGENTS.md"
14
+ ],
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/index.d.ts",
18
+ "import": "./dist/index.js"
19
+ }
20
+ },
21
+ "devDependencies": {
22
+ "@happyvertical/smrt-core": "0.74.5",
23
+ "@types/node": "24.13.6",
24
+ "typescript": "6.0.3",
25
+ "vite": "8.1.6",
26
+ "vitest": "4.1.10"
27
+ },
28
+ "engines": {
29
+ "node": ">=20"
30
+ },
31
+ "publishConfig": {
32
+ "registry": "https://registry.npmjs.org",
33
+ "access": "public"
34
+ },
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "https://github.com/happyvertical/smrt.git",
38
+ "directory": "packages/smrt-support-contract"
39
+ },
40
+ "scripts": {
41
+ "build": "vite build",
42
+ "build:watch": "vite build --watch",
43
+ "dev": "npm run build:watch & npm run test:watch",
44
+ "test": "vitest run",
45
+ "test:watch": "vitest",
46
+ "typecheck": "tsc -p tsconfig.typecheck.json",
47
+ "clean": "rm -rf dist",
48
+ "verify:pack": "node ../../scripts/verify-package-types-exports.js .",
49
+ "build:fresh": "npm run clean && npm run build && npm run verify:pack"
50
+ }
6
51
  }