@layervai/qurl 3.1.0 → 4.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.
Files changed (152) hide show
  1. package/README.md +259 -46
  2. package/dist/cjs/client-connectors.d.ts +44 -0
  3. package/dist/cjs/client-connectors.js +189 -0
  4. package/dist/cjs/client-delegated.d.ts +30 -0
  5. package/dist/cjs/client-delegated.js +312 -0
  6. package/dist/cjs/client-errors.d.ts +44 -0
  7. package/dist/cjs/client-errors.js +219 -0
  8. package/dist/cjs/client-http-types.d.ts +37 -0
  9. package/dist/cjs/client-http-types.js +2 -0
  10. package/dist/cjs/client-input-fields.d.ts +53 -0
  11. package/dist/cjs/client-input-fields.js +262 -0
  12. package/dist/cjs/client-limits.d.ts +36 -0
  13. package/dist/cjs/client-limits.js +61 -0
  14. package/dist/cjs/client-management.d.ts +12 -0
  15. package/dist/cjs/client-management.js +119 -0
  16. package/dist/cjs/client-paths.d.ts +21 -0
  17. package/dist/cjs/client-paths.js +143 -0
  18. package/dist/cjs/client-portals.d.ts +82 -0
  19. package/dist/cjs/client-portals.js +244 -0
  20. package/dist/cjs/client-resources.d.ts +29 -0
  21. package/dist/cjs/client-resources.js +331 -0
  22. package/dist/cjs/client-validation.d.ts +35 -0
  23. package/dist/cjs/client-validation.js +326 -0
  24. package/dist/cjs/client.d.ts +45 -75
  25. package/dist/cjs/client.js +621 -2448
  26. package/dist/cjs/errors.d.ts +9 -1
  27. package/dist/cjs/errors.js +10 -1
  28. package/dist/cjs/index.d.ts +4 -2
  29. package/dist/cjs/index.js +4 -1
  30. package/dist/cjs/response-metadata.d.ts +13 -0
  31. package/dist/cjs/response-metadata.js +38 -0
  32. package/dist/cjs/share.js +2 -0
  33. package/dist/cjs/target-path.d.ts +2 -0
  34. package/dist/cjs/target-path.js +34 -0
  35. package/dist/cjs/types.d.ts +83 -7
  36. package/dist/cjs/version.d.ts +1 -1
  37. package/dist/cjs/version.js +1 -1
  38. package/dist/esm/client-connectors.d.ts +44 -0
  39. package/dist/esm/client-connectors.js +180 -0
  40. package/dist/esm/client-delegated.d.ts +30 -0
  41. package/dist/esm/client-delegated.js +295 -0
  42. package/dist/esm/client-errors.d.ts +44 -0
  43. package/dist/esm/client-errors.js +206 -0
  44. package/dist/esm/client-http-types.d.ts +37 -0
  45. package/dist/esm/client-http-types.js +1 -0
  46. package/dist/esm/client-input-fields.d.ts +53 -0
  47. package/dist/esm/client-input-fields.js +258 -0
  48. package/dist/esm/client-limits.d.ts +36 -0
  49. package/dist/esm/client-limits.js +58 -0
  50. package/dist/esm/client-management.d.ts +12 -0
  51. package/dist/esm/client-management.js +113 -0
  52. package/dist/esm/client-paths.d.ts +21 -0
  53. package/dist/esm/client-paths.js +138 -0
  54. package/dist/esm/client-portals.d.ts +82 -0
  55. package/dist/esm/client-portals.js +236 -0
  56. package/dist/esm/client-resources.d.ts +29 -0
  57. package/dist/esm/client-resources.js +323 -0
  58. package/dist/esm/client-validation.d.ts +35 -0
  59. package/dist/esm/client-validation.js +302 -0
  60. package/dist/esm/client.d.ts +45 -76
  61. package/dist/esm/client.js +318 -2147
  62. package/dist/esm/crid.d.ts +0 -1
  63. package/dist/esm/crid.js +0 -1
  64. package/dist/esm/errors.d.ts +9 -2
  65. package/dist/esm/errors.js +9 -1
  66. package/dist/esm/index.d.ts +4 -3
  67. package/dist/esm/index.js +2 -2
  68. package/dist/esm/internal.d.ts +0 -1
  69. package/dist/esm/internal.js +0 -1
  70. package/dist/esm/node/agent-runtime.d.ts +0 -1
  71. package/dist/esm/node/agent-runtime.js +0 -1
  72. package/dist/esm/node/agent-state.d.ts +0 -1
  73. package/dist/esm/node/agent-state.js +0 -1
  74. package/dist/esm/node/agent-transport.d.ts +0 -1
  75. package/dist/esm/node/agent-transport.js +0 -1
  76. package/dist/esm/node/deployment.d.ts +0 -1
  77. package/dist/esm/node/deployment.js +0 -1
  78. package/dist/esm/node/file-agent-state.d.ts +0 -1
  79. package/dist/esm/node/file-agent-state.js +0 -1
  80. package/dist/esm/node/native-udp.d.ts +0 -1
  81. package/dist/esm/node/native-udp.js +0 -1
  82. package/dist/esm/node/nhp-wire.d.ts +0 -1
  83. package/dist/esm/node/nhp-wire.js +0 -1
  84. package/dist/esm/node/portal-opener.d.ts +0 -1
  85. package/dist/esm/node/portal-opener.js +0 -1
  86. package/dist/esm/node/provider.d.ts +0 -1
  87. package/dist/esm/node/provider.js +0 -1
  88. package/dist/esm/node/qv2.d.ts +0 -1
  89. package/dist/esm/node/qv2.js +0 -1
  90. package/dist/esm/node/relay.d.ts +0 -1
  91. package/dist/esm/node/relay.js +0 -1
  92. package/dist/esm/node/sealed-agent-state.d.ts +0 -1
  93. package/dist/esm/node/sealed-agent-state.js +0 -1
  94. package/dist/esm/node/strict-json.d.ts +0 -1
  95. package/dist/esm/node/strict-json.js +0 -1
  96. package/dist/esm/node.d.ts +0 -1
  97. package/dist/esm/node.js +0 -1
  98. package/dist/esm/response-metadata.d.ts +13 -0
  99. package/dist/esm/response-metadata.js +33 -0
  100. package/dist/esm/share.d.ts +0 -1
  101. package/dist/esm/share.js +2 -1
  102. package/dist/esm/target-path.d.ts +2 -0
  103. package/dist/esm/target-path.js +30 -0
  104. package/dist/esm/types.d.ts +83 -8
  105. package/dist/esm/types.js +0 -1
  106. package/dist/esm/version.d.ts +1 -2
  107. package/dist/esm/version.js +1 -2
  108. package/package.json +9 -7
  109. package/dist/esm/client.d.ts.map +0 -1
  110. package/dist/esm/client.js.map +0 -1
  111. package/dist/esm/crid.d.ts.map +0 -1
  112. package/dist/esm/crid.js.map +0 -1
  113. package/dist/esm/errors.d.ts.map +0 -1
  114. package/dist/esm/errors.js.map +0 -1
  115. package/dist/esm/index.d.ts.map +0 -1
  116. package/dist/esm/index.js.map +0 -1
  117. package/dist/esm/internal.d.ts.map +0 -1
  118. package/dist/esm/internal.js.map +0 -1
  119. package/dist/esm/node/agent-runtime.d.ts.map +0 -1
  120. package/dist/esm/node/agent-runtime.js.map +0 -1
  121. package/dist/esm/node/agent-state.d.ts.map +0 -1
  122. package/dist/esm/node/agent-state.js.map +0 -1
  123. package/dist/esm/node/agent-transport.d.ts.map +0 -1
  124. package/dist/esm/node/agent-transport.js.map +0 -1
  125. package/dist/esm/node/deployment.d.ts.map +0 -1
  126. package/dist/esm/node/deployment.js.map +0 -1
  127. package/dist/esm/node/file-agent-state.d.ts.map +0 -1
  128. package/dist/esm/node/file-agent-state.js.map +0 -1
  129. package/dist/esm/node/native-udp.d.ts.map +0 -1
  130. package/dist/esm/node/native-udp.js.map +0 -1
  131. package/dist/esm/node/nhp-wire.d.ts.map +0 -1
  132. package/dist/esm/node/nhp-wire.js.map +0 -1
  133. package/dist/esm/node/portal-opener.d.ts.map +0 -1
  134. package/dist/esm/node/portal-opener.js.map +0 -1
  135. package/dist/esm/node/provider.d.ts.map +0 -1
  136. package/dist/esm/node/provider.js.map +0 -1
  137. package/dist/esm/node/qv2.d.ts.map +0 -1
  138. package/dist/esm/node/qv2.js.map +0 -1
  139. package/dist/esm/node/relay.d.ts.map +0 -1
  140. package/dist/esm/node/relay.js.map +0 -1
  141. package/dist/esm/node/sealed-agent-state.d.ts.map +0 -1
  142. package/dist/esm/node/sealed-agent-state.js.map +0 -1
  143. package/dist/esm/node/strict-json.d.ts.map +0 -1
  144. package/dist/esm/node/strict-json.js.map +0 -1
  145. package/dist/esm/node.d.ts.map +0 -1
  146. package/dist/esm/node.js.map +0 -1
  147. package/dist/esm/share.d.ts.map +0 -1
  148. package/dist/esm/share.js.map +0 -1
  149. package/dist/esm/types.d.ts.map +0 -1
  150. package/dist/esm/types.js.map +0 -1
  151. package/dist/esm/version.d.ts.map +0 -1
  152. package/dist/esm/version.js.map +0 -1
@@ -0,0 +1,12 @@
1
+ import type { ApiKeyRequestScope } from "./types.js";
2
+ /** Narrow a response scope before reusing it in a create/update request. */
3
+ export declare function isApiKeyRequestScope(scope: string): scope is ApiKeyRequestScope;
4
+ export declare function validateWebhookWriteFields(input: Record<string, unknown>, method: string, requiredFields?: {
5
+ url?: boolean;
6
+ events?: boolean;
7
+ }): void;
8
+ export declare function validateApiKeyWriteFields(input: Record<string, unknown>, method: string, requiredFields?: {
9
+ name?: boolean;
10
+ scopes?: boolean;
11
+ }): void;
12
+ export declare function validateEnrollmentTokenFields(input: Record<string, unknown>, method: string): void;
@@ -0,0 +1,119 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isApiKeyRequestScope = isApiKeyRequestScope;
4
+ exports.validateWebhookWriteFields = validateWebhookWriteFields;
5
+ exports.validateApiKeyWriteFields = validateApiKeyWriteFields;
6
+ exports.validateEnrollmentTokenFields = validateEnrollmentTokenFields;
7
+ const client_input_fields_js_1 = require("./client-input-fields.js");
8
+ const client_validation_js_1 = require("./client-validation.js");
9
+ const client_limits_js_1 = require("./client-limits.js");
10
+ const client_errors_js_1 = require("./client-errors.js");
11
+ const client_connectors_js_1 = require("./client-connectors.js");
12
+ const API_KEY_REQUEST_SCOPE_VALUES = [
13
+ "qurl:read",
14
+ "qurl:write",
15
+ "qurl:resolve",
16
+ "qurl:agent",
17
+ ];
18
+ (0, client_input_fields_js_1.assertExhaustive)(true);
19
+ const API_KEY_REQUEST_SCOPES = new Set(API_KEY_REQUEST_SCOPE_VALUES);
20
+ /** Narrow a response scope before reusing it in a create/update request. */
21
+ function isApiKeyRequestScope(scope) {
22
+ return API_KEY_REQUEST_SCOPES.has(scope);
23
+ }
24
+ const CREDENTIAL_TARGET_VALUES = [
25
+ "agent",
26
+ "connector",
27
+ ];
28
+ (0, client_input_fields_js_1.assertExhaustive)(true);
29
+ const CREDENTIAL_TARGETS = new Set(CREDENTIAL_TARGET_VALUES);
30
+ const CREDENTIAL_CLAIM_TYPE_VALUES = [
31
+ "connector",
32
+ ];
33
+ (0, client_input_fields_js_1.assertExhaustive)(true);
34
+ const CREDENTIAL_CLAIM_TYPES = new Set(CREDENTIAL_CLAIM_TYPE_VALUES);
35
+ // Mirrors CreateApiKeyRequest.expires_in in the service OpenAPI. Composite
36
+ // durations are deliberately invalid on this endpoint. The 24h cap permits
37
+ // 1d, but no positive whole-week duration.
38
+ const CREDENTIAL_DURATION_PATTERN = /^([0-9]+)([smhdw])$/;
39
+ const CREDENTIAL_DURATION_MULTIPLIERS = {
40
+ s: 1n,
41
+ m: 60n,
42
+ h: 3600n,
43
+ d: 86400n,
44
+ w: 604800n,
45
+ };
46
+ function validateWebhookWriteFields(input, method, requiredFields = {}) {
47
+ if (requiredFields.url || input.url !== undefined) {
48
+ (0, client_validation_js_1.requireNonEmptyStringField)(input, "url", method);
49
+ (0, client_validation_js_1.requireValidHttpUrl)(input.url, "url");
50
+ }
51
+ if (requiredFields.events || input.events !== undefined) {
52
+ (0, client_validation_js_1.requireNonEmptyArrayField)(input, "events", method);
53
+ (0, client_validation_js_1.requireStringArrayElements)(input.events, "events", method);
54
+ }
55
+ (0, client_validation_js_1.requireMaxLength)(input.description, "description", client_limits_js_1.MAX_DESCRIPTION);
56
+ if (input.status !== undefined) {
57
+ (0, client_validation_js_1.requireNonEmptyStringField)(input, "status", method);
58
+ }
59
+ }
60
+ function validateApiKeyWriteFields(input, method, requiredFields = {}) {
61
+ if (requiredFields.name || input.name !== undefined) {
62
+ (0, client_validation_js_1.requireNonEmptyStringField)(input, "name", method);
63
+ (0, client_validation_js_1.requireMaxLength)(input.name, "name", client_limits_js_1.MAX_API_KEY_NAME);
64
+ }
65
+ if (requiredFields.scopes || input.scopes !== undefined) {
66
+ (0, client_validation_js_1.requireNonEmptyArrayField)(input, "scopes", method);
67
+ (0, client_validation_js_1.requireStringArrayElements)(input.scopes, "scopes", method);
68
+ const unsupported = input.scopes.find((scope) => !API_KEY_REQUEST_SCOPES.has(scope));
69
+ if (unsupported !== undefined) {
70
+ throw (0, client_errors_js_1.clientValidationError)(`${method}: scopes contains an unsupported permission ${JSON.stringify(unsupported)}; this SDK accepts ${API_KEY_REQUEST_SCOPE_VALUES.join(", ")}`);
71
+ }
72
+ }
73
+ }
74
+ function validateEnrollmentTokenFields(input, method) {
75
+ if (input.target !== undefined &&
76
+ (typeof input.target !== "string" || !CREDENTIAL_TARGETS.has(input.target))) {
77
+ throw (0, client_errors_js_1.clientValidationError)(`${method}: target must be 'agent' or 'connector'`);
78
+ }
79
+ let claimCount = 0;
80
+ if (input.claims !== undefined) {
81
+ if (!Array.isArray(input.claims)) {
82
+ throw (0, client_errors_js_1.clientValidationError)(`${method}: claims must be an array`);
83
+ }
84
+ if (input.claims.length > 1) {
85
+ throw (0, client_errors_js_1.clientValidationError)(`${method}: claims must contain at most one claim`);
86
+ }
87
+ claimCount = input.claims.length;
88
+ for (const [index, claim] of input.claims.entries()) {
89
+ if (!claim || typeof claim !== "object" || Array.isArray(claim)) {
90
+ throw (0, client_errors_js_1.clientValidationError)(`${method}: claims[${index}] must be an object`);
91
+ }
92
+ (0, client_validation_js_1.requireNoUnknownFields)(claim, ["type", "id"], `${method}: claims[${index}]`);
93
+ const record = claim;
94
+ if (typeof record.type !== "string" || !CREDENTIAL_CLAIM_TYPES.has(record.type)) {
95
+ throw (0, client_errors_js_1.clientValidationError)(`${method}: claims[${index}].type must be 'connector'`);
96
+ }
97
+ if (typeof record.id !== "string" || !client_connectors_js_1.CONNECTOR_SLUG_PATTERN.test(record.id)) {
98
+ throw (0, client_errors_js_1.clientValidationError)(`${method}: claims[${index}].id is not a valid connector slug; use 3-64 lowercase letters, digits, or hyphens, starting with a letter and ending with a letter or digit`);
99
+ }
100
+ }
101
+ }
102
+ // CreateApiKeyRequest.target permits an agent with zero or one connector claim.
103
+ if (input.target === "connector" && claimCount !== 1) {
104
+ throw (0, client_errors_js_1.clientValidationError)(`${method}: target 'connector' requires exactly one claim`);
105
+ }
106
+ if (input.expires_in !== undefined) {
107
+ if (typeof input.expires_in !== "string") {
108
+ throw (0, client_errors_js_1.clientValidationError)(`${method}: expires_in must be a duration string`);
109
+ }
110
+ const match = CREDENTIAL_DURATION_PATTERN.exec(input.expires_in);
111
+ if (!match) {
112
+ throw (0, client_errors_js_1.clientValidationError)(`${method}: expires_in must match <integer><s|m|h|d|w>`);
113
+ }
114
+ const seconds = BigInt(match[1]) * CREDENTIAL_DURATION_MULTIPLIERS[match[2]];
115
+ if (seconds <= 0n || seconds > client_limits_js_1.MAX_ENROLLMENT_TOKEN_TTL_SECONDS) {
116
+ throw (0, client_errors_js_1.clientValidationError)(`${method}: expires_in must be greater than zero and at most 24h`);
117
+ }
118
+ }
119
+ }
@@ -0,0 +1,21 @@
1
+ interface PathIdValidationOptions {
2
+ /** Reject a bare access token in namespaces that accept resource/qURL IDs. */
3
+ rejectBareAccessToken?: boolean;
4
+ /** Safe, non-secret recovery guidance appended to an access-token error. */
5
+ accessTokenRecovery?: string;
6
+ /** Reject qURL display IDs where the operation requires a parent resource. */
7
+ rejectQurlDisplayId?: boolean;
8
+ requireCridUnlessQurlDisplayId?: boolean;
9
+ }
10
+ export declare const RESOURCE_OR_QURL_ID_PATH_OPTIONS: PathIdValidationOptions;
11
+ export declare const QURL_ID_PATH_OPTIONS: PathIdValidationOptions;
12
+ /**
13
+ * Validates that a path-parameter argument is a non-empty string. Some callers
14
+ * pass resource/qURL display IDs, while newer endpoints also pass domains,
15
+ * session IDs, webhook IDs, and API-key IDs, so this intentionally enforces
16
+ * only basic shape plus transport-safety rules and leaves endpoint-specific
17
+ * identifier grammar to the service.
18
+ */
19
+ export declare function validatePathId(id: string, method: string, field?: string, options?: PathIdValidationOptions): void;
20
+ export declare function requireResourceCrid(crid: string, method: string, field?: string): void;
21
+ export {};
@@ -0,0 +1,143 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.QURL_ID_PATH_OPTIONS = exports.RESOURCE_OR_QURL_ID_PATH_OPTIONS = void 0;
4
+ exports.validatePathId = validatePathId;
5
+ exports.requireResourceCrid = requireResourceCrid;
6
+ const crid_js_1 = require("./crid.js");
7
+ const client_errors_js_1 = require("./client-errors.js");
8
+ const client_limits_js_1 = require("./client-limits.js");
9
+ // Best-effort defence-in-depth against today's access-token grammar. The
10
+ // service remains authoritative because resource IDs and credentials are both
11
+ // opaque and future credential formats may not retain the `at_` prefix. The
12
+ // delimiter requirement cannot collide with current base64url public keys,
13
+ // standard-base64 keys, or base32 CRIDs.
14
+ const PATH_EMBEDDED_ACCESS_TOKEN_RE = /[?&#=:\s]at_/i;
15
+ const PATH_PREFIXED_ACCESS_TOKEN_RE = /\/at_/i;
16
+ const QURL_LINK_URL_RE = /^(?:https?:\/\/)?(?:[a-z0-9-]+\.)*qurl\.link(?::\d{1,5})?(?:\/|[?#])/i;
17
+ // ponytail: today's 22-character token suffix only improves URL-paste diagnostics;
18
+ // other lengths are still rejected as URLs without echoing the input.
19
+ const URL_EMBEDDED_ACCESS_TOKEN_RE = /[?&#=:/]at_[a-z0-9_-]{22}(?:$|[?&#:/])/i;
20
+ // A host without a slash can be a legitimate domain identifier. Require the
21
+ // path boundary so shared validation does not break the domain namespace.
22
+ const PATH_SCHEMELESS_URL_RE = /^[a-z0-9-]+(?:\.[a-z0-9-]+)+(?::\d{1,5})?\//i;
23
+ const QURL_DISPLAY_ID_PREFIX_RE = /^q_/i;
24
+ function isUrlLikePathId(value) {
25
+ return /^https?:\/\//i.test(value) || PATH_SCHEMELESS_URL_RE.test(value);
26
+ }
27
+ const REVOKE_INDIVIDUAL_QURL_RECOVERY = "revoke individual tokens with revokeResourceQurl(crid, qurlId)";
28
+ const DELETE_RESOURCE_RECOVERY = "pass a CRID returned by the API; to revoke one qURL, call revokeResourceQurl(crid, qurlId)";
29
+ exports.RESOURCE_OR_QURL_ID_PATH_OPTIONS = {
30
+ requireCridUnlessQurlDisplayId: true,
31
+ };
32
+ exports.QURL_ID_PATH_OPTIONS = {
33
+ rejectBareAccessToken: true,
34
+ accessTokenRecovery: "pass the qURL display ID, not its access token",
35
+ };
36
+ /**
37
+ * Validates that a path-parameter argument is a non-empty string. Some callers
38
+ * pass resource/qURL display IDs, while newer endpoints also pass domains,
39
+ * session IDs, webhook IDs, and API-key IDs, so this intentionally enforces
40
+ * only basic shape plus transport-safety rules and leaves endpoint-specific
41
+ * identifier grammar to the service.
42
+ */
43
+ function validatePathId(id, method, field = "id", options = {}) {
44
+ if (options.requireCridUnlessQurlDisplayId && typeof id === "string" && !id.startsWith("q_")) {
45
+ requireResourceCrid(id, method, field);
46
+ return;
47
+ }
48
+ // `.trim()` catches whitespace-only and padded IDs before they round-trip as
49
+ // `%20...%20` paths that the server can only reject with a less useful 404.
50
+ // The pre-flight error is more actionable than the 404.
51
+ if (typeof id !== "string") {
52
+ const observedType = id === null ? "null" : typeof id;
53
+ throw (0, client_errors_js_1.clientValidationError)(`${method}: ${field} is required (got ${observedType})`);
54
+ }
55
+ if (id.trim() === "") {
56
+ throw (0, client_errors_js_1.clientValidationError)(`${method}: ${field} is required`);
57
+ }
58
+ if (id.trim() !== id) {
59
+ throw (0, client_errors_js_1.clientValidationError)(`${method}: ${field} must not include leading or trailing whitespace`);
60
+ }
61
+ if (id.length > client_limits_js_1.MAX_PATH_ID_LENGTH) {
62
+ throw (0, client_errors_js_1.clientValidationError)(`${method}: ${field} must be ${client_limits_js_1.MAX_PATH_ID_LENGTH} characters or fewer`);
63
+ }
64
+ const decodedIds = decodedPathIdForms(id);
65
+ // URL resolvers and intermediaries can normalize raw or pre-encoded dot
66
+ // segments before routing. Reject every decoded form we inspected so an
67
+ // item operation cannot be retargeted to a collection endpoint. Embedded
68
+ // `a/../b` remains an opaque single segment because the later URL builder
69
+ // percent-encodes its slash.
70
+ if (decodedIds.some((value) => value === "." || value === "..")) {
71
+ throw (0, client_errors_js_1.clientValidationError)(`${method}: ${field} is an invalid URL path segment`);
72
+ }
73
+ // `/` is deliberately outside the general delimiter class so a URL path
74
+ // such as `/at_a_glance` is not misread as a credential. For non-URL input,
75
+ // `/at_` remains a strong pasted-path signal. Fragment, query, header, and
76
+ // pasted `Bearer at_...` / `token:at_...` forms are also strong signals.
77
+ // Bare `at_...` values are rejected only for resource/qURL identifiers:
78
+ // those current formats have fixed non-colliding prefixes, while domain,
79
+ // webhook, session, and API-key IDs are deliberately opaque/open contracts.
80
+ // Full URLs and delimiter/path-prefixed credentials remain rejected in
81
+ // every namespace.
82
+ const containsUrl = decodedIds.some(isUrlLikePathId);
83
+ const containsAccessToken = decodedIds.some((value) => {
84
+ const valueIsUrl = isUrlLikePathId(value);
85
+ return ((QURL_LINK_URL_RE.test(value) &&
86
+ (PATH_EMBEDDED_ACCESS_TOKEN_RE.test(value) || PATH_PREFIXED_ACCESS_TOKEN_RE.test(value))) ||
87
+ (valueIsUrl
88
+ ? URL_EMBEDDED_ACCESS_TOKEN_RE.test(value)
89
+ : PATH_EMBEDDED_ACCESS_TOKEN_RE.test(value) || PATH_PREFIXED_ACCESS_TOKEN_RE.test(value)) ||
90
+ (options.rejectBareAccessToken === true && value.slice(0, 3).toLowerCase() === "at_"));
91
+ });
92
+ if (containsAccessToken) {
93
+ const recovery = options.accessTokenRecovery ?? "pass the identifier returned by the API";
94
+ throw (0, client_errors_js_1.clientValidationError)(`${method}: ${field} must not contain an access token; ${recovery}`);
95
+ }
96
+ // A full target/qURL is a common argument mix-up, but it is distinct from
97
+ // passing an access-token credential. Diagnose it accurately without
98
+ // echoing the URL, which may itself contain sensitive query parameters.
99
+ if (containsUrl) {
100
+ throw (0, client_errors_js_1.clientValidationError)(`${method}: ${field} must be an identifier, not a URL`);
101
+ }
102
+ if (options.rejectQurlDisplayId === true &&
103
+ decodedIds.some((value) => QURL_DISPLAY_ID_PREFIX_RE.test(value))) {
104
+ throw (0, client_errors_js_1.clientValidationError)(`${method}: ${field} must not be a qURL display ID; ${REVOKE_INDIVIDUAL_QURL_RECOVERY}`);
105
+ }
106
+ }
107
+ function decodedPathIdForms(id) {
108
+ // Probe repeatedly encoded input too. Callers sometimes pre-encode a copied
109
+ // link before passing it through a URL builder that encodes it again. Three
110
+ // passes cover the common accidental cases without allowing hostile input
111
+ // to create unbounded work. More deeply encoded or malformed-percent input
112
+ // deliberately fails open to the authoritative service after safe segment
113
+ // encoding; this heuristic is not an identifier parser.
114
+ const decodedIds = [id];
115
+ let decodedId = id;
116
+ for (let pass = 0; pass < client_limits_js_1.MAX_PATH_ID_DECODE_PASSES; pass += 1) {
117
+ try {
118
+ const next = decodeURIComponent(decodedId);
119
+ if (next === decodedId)
120
+ break;
121
+ decodedIds.push(next);
122
+ decodedId = next;
123
+ }
124
+ catch {
125
+ // Malformed percent escapes remain opaque and are left to the service.
126
+ break;
127
+ }
128
+ }
129
+ return decodedIds;
130
+ }
131
+ function requireResourceCrid(crid, method, field = "id") {
132
+ if ((0, crid_js_1.parseCrid)(crid))
133
+ return;
134
+ // Keep actionable paste errors without inspecting valid CRIDs twice.
135
+ validatePathId(crid, method, field, {
136
+ rejectBareAccessToken: true,
137
+ rejectQurlDisplayId: true,
138
+ accessTokenRecovery: method === "delete" || method === "deleteResource"
139
+ ? DELETE_RESOURCE_RECOVERY
140
+ : "pass a CRID returned by the API",
141
+ });
142
+ throw (0, client_errors_js_1.clientValidationError)(`${method}: requires a valid CRID`);
143
+ }
@@ -0,0 +1,82 @@
1
+ import type { CreatePortalOptions, Portal, RequestOptions, Resource } from "./types.js";
2
+ import type { QURLClient } from "./client.js";
3
+ /**
4
+ * Shape of qurl-go's offline signed-fragment links: three or more
5
+ * dot-separated base64url parts (<version>.<claims>.<secret>.<sig>).
6
+ * Detected only to give those links a precise error in extractAccessToken.
7
+ *
8
+ * @internal Exported for in-package tests; not re-exported from index.ts.
9
+ */
10
+ export declare const SIGNED_FRAGMENT_RE: RegExp;
11
+ /**
12
+ * Extract the access token from a qURL link, or pass a bare token through.
13
+ *
14
+ * Platform-issued links carry the access token in the URL fragment
15
+ * (`https://qurl.link/#at_...`). Error messages deliberately never echo the
16
+ * input — qURL links are credentials and must stay out of logs.
17
+ */
18
+ export declare function extractAccessToken(qurlLink: unknown): string;
19
+ /**
20
+ * Parse an RFC 3339 timestamp from the API into a `Date`, or `undefined`
21
+ * when absent or unparseable. The portal surface exposes `Date` (matching
22
+ * qurl-go's `time.Time` and qurl-python's `datetime`); the REST-shaped
23
+ * layer keeps raw wire strings.
24
+ */
25
+ export declare function parseApiDate(value: string | undefined): Date | undefined;
26
+ /** Wire shape shared by the two portal-minting endpoints. */
27
+ export type PortalWireResponse = {
28
+ resource_id?: string;
29
+ crid?: string;
30
+ qurl_link?: string;
31
+ qurl_site?: string;
32
+ expires_at?: string;
33
+ qurl_id?: string;
34
+ label?: string;
35
+ target_path?: string;
36
+ };
37
+ /**
38
+ * Parse a {@link Portal} from a create-portal API response. `resource_id`
39
+ * and `qurl_link` are required, mirroring qurl-go's fail-closed response
40
+ * check; everything else is optional because the two mint endpoints differ
41
+ * in which ancillary fields they return.
42
+ */
43
+ export declare function parsePortal(data: PortalWireResponse | undefined, method: string, expectedCrid?: string, expectedTargetPath?: string): Promise<Portal>;
44
+ /**
45
+ * Validate portal options and build the create-portal wire body. The service
46
+ * requires a JSON object even when every option is omitted; `{}` selects the
47
+ * owner's plan defaults and matches qurl-go's zero-value request struct.
48
+ */
49
+ export declare function buildCreatePortalBody(opts: CreatePortalOptions, method: string): Record<string, unknown>;
50
+ /**
51
+ * A LayerV-protected resource, bound to the client that produced it.
52
+ *
53
+ * Obtained from {@link QURLClient.protectUrl} or {@link QURLClient.resourceByCrid} —
54
+ * not constructed directly. Mint short-lived access links for the resource
55
+ * with {@link createPortal} (qurl-go: `qurl.Resource`).
56
+ */
57
+ export declare class ProtectedResource {
58
+ #private;
59
+ /** The public resource CRID. */
60
+ readonly crid: string;
61
+ /** The private URL protected by this resource, when known. */
62
+ readonly targetUrl?: string;
63
+ /**
64
+ * Full server-populated {@link Resource} metadata when the handle came
65
+ * from an API response; `undefined` for {@link QURLClient.resourceByCrid}
66
+ * handles and for the one-call {@link QURLClient.createPortalForUrl} path.
67
+ */
68
+ readonly details?: Resource;
69
+ constructor(client: QURLClient, id: string, targetUrl?: string, details?: Resource);
70
+ /**
71
+ * Whether `resource` was produced by `client`. A static because the
72
+ * binding lives in a private field that only this class can read; used
73
+ * by {@link QURLClient.createPortal} to refuse handles bound to a
74
+ * different client.
75
+ */
76
+ static isBoundTo(resource: ProtectedResource, client: QURLClient): boolean;
77
+ /**
78
+ * Mint a short-lived qURL link (a portal) for this resource. See
79
+ * {@link QURLClient.createPortal} for the option reference.
80
+ */
81
+ createPortal(opts?: CreatePortalOptions, requestOptions?: RequestOptions): Promise<Portal>;
82
+ }
@@ -0,0 +1,244 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ProtectedResource = exports.SIGNED_FRAGMENT_RE = void 0;
4
+ exports.extractAccessToken = extractAccessToken;
5
+ exports.parseApiDate = parseApiDate;
6
+ exports.parsePortal = parsePortal;
7
+ exports.buildCreatePortalBody = buildCreatePortalBody;
8
+ const response_metadata_js_1 = require("./response-metadata.js");
9
+ const client_errors_js_1 = require("./client-errors.js");
10
+ const client_connectors_js_1 = require("./client-connectors.js");
11
+ const client_validation_js_1 = require("./client-validation.js");
12
+ const client_input_fields_js_1 = require("./client-input-fields.js");
13
+ const client_limits_js_1 = require("./client-limits.js");
14
+ const target_path_js_1 = require("./target-path.js");
15
+ // ---- Portal-verb helpers (mirrors qurl-go) -------------------------------
16
+ // Client-side guardrails for the portal flow (protectUrl → createPortal →
17
+ // enterPortal), kept in lockstep with qurl-go's option validation and
18
+ // qurl-python's port of it.
19
+ /**
20
+ * Client-side floor for portal lifetimes, mirroring qurl-go's `ValidFor`.
21
+ * The LayerV API remains the source of truth for account limits; there is
22
+ * intentionally no SDK-side maximum because an account may allow
23
+ * longer-lived portals.
24
+ */
25
+ const MIN_PORTAL_VALID_FOR_SECONDS = 60;
26
+ /**
27
+ * Client-side floor for session durations, mirroring qurl-go's
28
+ * `WithSessionDuration` (at least one second; zero is rejected rather than
29
+ * treated as the server default).
30
+ */
31
+ const MIN_SESSION_DURATION_SECONDS = 1;
32
+ /**
33
+ * Shape of qurl-go's offline signed-fragment links: three or more
34
+ * dot-separated base64url parts (<version>.<claims>.<secret>.<sig>).
35
+ * Detected only to give those links a precise error in extractAccessToken.
36
+ *
37
+ * @internal Exported for in-package tests; not re-exported from index.ts.
38
+ */
39
+ exports.SIGNED_FRAGMENT_RE = /^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+){2,}$/;
40
+ // Access-token grammar accepted by enterPortal (base64url charset).
41
+ const ACCESS_TOKEN_RE = /^[A-Za-z0-9_-]+$/;
42
+ /**
43
+ * Serialize a duration option to the API's h/m/s duration grammar.
44
+ *
45
+ * Strings pass through unvalidated — the server is authoritative, same as
46
+ * the REST-shaped `expires_in` fields. Numbers are milliseconds and get
47
+ * qurl-go's client-side guardrails: whole seconds only and at least
48
+ * `minimumSeconds` (checked in that order so e.g. 30.5s reports "at least
49
+ * 60s" in every SDK). Serialized with hours as the largest unit so all API
50
+ * duration fields use the same grammar across SDKs.
51
+ */
52
+ function serializeApiDuration(value, field, minimumSeconds) {
53
+ if (value === undefined)
54
+ return undefined;
55
+ if (typeof value === "string") {
56
+ if (value.trim() === "") {
57
+ throw (0, client_errors_js_1.clientValidationError)(`${field}: must be a non-empty duration string`);
58
+ }
59
+ return value;
60
+ }
61
+ if (typeof value === "number") {
62
+ // NaN fails no comparison, so an explicit finite check keeps the
63
+ // error actionable instead of a misleading "whole seconds" report.
64
+ if (!Number.isFinite(value)) {
65
+ throw (0, client_errors_js_1.clientValidationError)(`${field}: must be a finite number of milliseconds`);
66
+ }
67
+ if (value < minimumSeconds * 1000) {
68
+ throw (0, client_errors_js_1.clientValidationError)(`${field}: must be at least ${minimumSeconds}s`);
69
+ }
70
+ if (value % 1000 !== 0) {
71
+ throw (0, client_errors_js_1.clientValidationError)(`${field}: must be whole seconds`);
72
+ }
73
+ const seconds = value / 1000;
74
+ if (seconds % 3600 === 0)
75
+ return `${seconds / 3600}h`;
76
+ if (seconds % 60 === 0)
77
+ return `${seconds / 60}m`;
78
+ return `${seconds}s`;
79
+ }
80
+ throw (0, client_errors_js_1.clientValidationError)(`${field}: must be a duration string (e.g. "5m") or a number of milliseconds`);
81
+ }
82
+ /**
83
+ * Extract the access token from a qURL link, or pass a bare token through.
84
+ *
85
+ * Platform-issued links carry the access token in the URL fragment
86
+ * (`https://qurl.link/#at_...`). Error messages deliberately never echo the
87
+ * input — qURL links are credentials and must stay out of logs.
88
+ */
89
+ function extractAccessToken(qurlLink) {
90
+ if (typeof qurlLink !== "string" || qurlLink.trim() === "") {
91
+ throw (0, client_errors_js_1.clientValidationError)("qurlLink: must be a non-empty string");
92
+ }
93
+ const hashIndex = qurlLink.indexOf("#");
94
+ const token = hashIndex >= 0 ? qurlLink.slice(hashIndex + 1) : qurlLink;
95
+ if (exports.SIGNED_FRAGMENT_RE.test(token)) {
96
+ throw (0, client_errors_js_1.clientValidationError)("qurlLink: this is a signed qURL link (offline fragment format), which cannot be " +
97
+ "opened through the API resolver — enterPortal only accepts platform links " +
98
+ "(https://qurl.link/#at_...) or bare access tokens");
99
+ }
100
+ if (token === "" || !ACCESS_TOKEN_RE.test(token)) {
101
+ throw (0, client_errors_js_1.clientValidationError)("qurlLink: no access token found — pass a platform qURL link " +
102
+ "(https://qurl.link/#at_...) or a bare access token");
103
+ }
104
+ return token;
105
+ }
106
+ /**
107
+ * Parse an RFC 3339 timestamp from the API into a `Date`, or `undefined`
108
+ * when absent or unparseable. The portal surface exposes `Date` (matching
109
+ * qurl-go's `time.Time` and qurl-python's `datetime`); the REST-shaped
110
+ * layer keeps raw wire strings.
111
+ */
112
+ function parseApiDate(value) {
113
+ if (typeof value !== "string" || value === "")
114
+ return undefined;
115
+ const parsed = new Date(value);
116
+ return Number.isNaN(parsed.getTime()) ? undefined : parsed;
117
+ }
118
+ /**
119
+ * Parse a {@link Portal} from a create-portal API response. `resource_id`
120
+ * and `qurl_link` are required, mirroring qurl-go's fail-closed response
121
+ * check; everything else is optional because the two mint endpoints differ
122
+ * in which ancillary fields they return.
123
+ */
124
+ async function parsePortal(data, method, expectedCrid, expectedTargetPath) {
125
+ const errorOptions = { requestId: (0, response_metadata_js_1.getResponseMetadata)(data)?.requestId };
126
+ if (typeof data?.resource_id !== "string" || data.resource_id.trim() === "") {
127
+ throw (0, client_errors_js_1.unexpectedResponseError)(`${method}: response is missing resource_id`, errorOptions);
128
+ }
129
+ if (typeof data.qurl_link !== "string" || data.qurl_link.trim() === "") {
130
+ throw (0, client_errors_js_1.unexpectedResponseError)(`${method}: response is missing qurl_link`, errorOptions);
131
+ }
132
+ await (0, client_connectors_js_1.verifyResourceIdentity)(data, method, expectedCrid);
133
+ if (data.target_path !== expectedTargetPath ||
134
+ (data.target_path !== undefined && !(0, target_path_js_1.isCanonicalTargetPath)(data.target_path))) {
135
+ throw (0, client_errors_js_1.unexpectedResponseError)(`${method}: mint response target path differs from request`, errorOptions);
136
+ }
137
+ return (0, response_metadata_js_1.copyResponseMetadata)(data, {
138
+ crid: data.crid,
139
+ resourcePublicKey: data.resource_id,
140
+ link: data.qurl_link,
141
+ site: data.qurl_site,
142
+ expiresAt: parseApiDate(data.expires_at),
143
+ // Same empty-string → absent normalization the REST-shaped layer's
144
+ // consumers apply to qurl_id.
145
+ qurlId: data.qurl_id || undefined,
146
+ label: data.label,
147
+ targetPath: data.target_path,
148
+ });
149
+ }
150
+ /**
151
+ * Validate portal options and build the create-portal wire body. The service
152
+ * requires a JSON object even when every option is omitted; `{}` selects the
153
+ * owner's plan defaults and matches qurl-go's zero-value request struct.
154
+ */
155
+ function buildCreatePortalBody(opts, method) {
156
+ (0, client_validation_js_1.requireObjectInput)(opts, method);
157
+ (0, client_validation_js_1.requireNoUnknownFields)(opts, client_input_fields_js_1.CREATE_PORTAL_OPTION_KEYS, method);
158
+ // null → omitted, via the SDK-wide normalizePatchFields convention.
159
+ const { validFor, label, oneTimeUse, maxSessions, sessionDuration, targetPath, name } = (0, client_validation_js_1.normalizePatchFields)(opts, client_input_fields_js_1.CREATE_PORTAL_OPTION_KEYS);
160
+ if (label !== undefined) {
161
+ (0, client_validation_js_1.requireMaxLength)(label, "label", client_limits_js_1.MAX_LABEL);
162
+ // qurl-go's WithLabel rejects blank labels; the REST-shaped mintLink
163
+ // keeps its permissive whitespace behavior, so the check lives here.
164
+ if (label.trim() === "") {
165
+ throw (0, client_errors_js_1.clientValidationError)("label: must not be empty");
166
+ }
167
+ }
168
+ (0, client_validation_js_1.requireBooleanIfPresent)(oneTimeUse, "oneTimeUse");
169
+ (0, client_validation_js_1.requireMaxSessionsInRange)(maxSessions, "maxSessions");
170
+ (0, target_path_js_1.requireCanonicalTargetPath)(targetPath, "targetPath");
171
+ if (targetPath !== undefined && method === "createPortalForUrl") {
172
+ throw (0, client_errors_js_1.clientValidationError)("targetPath: requires an existing resource");
173
+ }
174
+ if (name !== undefined && method !== "createPortalForUrl") {
175
+ throw (0, client_errors_js_1.clientValidationError)("name: only applies when creating a resource (use createPortalForUrl or protectUrl); this resource exists");
176
+ }
177
+ (0, client_validation_js_1.requireResourceNameIfPresent)(name);
178
+ const body = {};
179
+ const expiresIn = serializeApiDuration(validFor, "validFor", MIN_PORTAL_VALID_FOR_SECONDS);
180
+ if (expiresIn !== undefined)
181
+ body.expires_in = expiresIn;
182
+ if (label !== undefined)
183
+ body.label = label;
184
+ if (oneTimeUse !== undefined)
185
+ body.one_time_use = oneTimeUse;
186
+ // Explicit 0 means unlimited and must survive body construction.
187
+ if (maxSessions !== undefined)
188
+ body.max_sessions = maxSessions;
189
+ const wireSessionDuration = serializeApiDuration(sessionDuration, "sessionDuration", MIN_SESSION_DURATION_SECONDS);
190
+ if (wireSessionDuration !== undefined)
191
+ body.session_duration = wireSessionDuration;
192
+ if (targetPath !== undefined)
193
+ body.target_path = targetPath;
194
+ if (name !== undefined)
195
+ body.name = name;
196
+ return body;
197
+ }
198
+ /**
199
+ * A LayerV-protected resource, bound to the client that produced it.
200
+ *
201
+ * Obtained from {@link QURLClient.protectUrl} or {@link QURLClient.resourceByCrid} —
202
+ * not constructed directly. Mint short-lived access links for the resource
203
+ * with {@link createPortal} (qurl-go: `qurl.Resource`).
204
+ */
205
+ class ProtectedResource {
206
+ // A true private field (not a module-scope WeakMap registry, which
207
+ // CONTRIBUTING.md's dual-build rule bars) so the binding stays on the
208
+ // instance and out of Object.keys/JSON.stringify output.
209
+ #client;
210
+ /** The public resource CRID. */
211
+ crid;
212
+ /** The private URL protected by this resource, when known. */
213
+ targetUrl;
214
+ /**
215
+ * Full server-populated {@link Resource} metadata when the handle came
216
+ * from an API response; `undefined` for {@link QURLClient.resourceByCrid}
217
+ * handles and for the one-call {@link QURLClient.createPortalForUrl} path.
218
+ */
219
+ details;
220
+ constructor(client, id, targetUrl, details) {
221
+ this.#client = client;
222
+ this.crid = id;
223
+ this.targetUrl = targetUrl;
224
+ this.details = details;
225
+ (0, response_metadata_js_1.copyResponseMetadata)(details, this);
226
+ }
227
+ /**
228
+ * Whether `resource` was produced by `client`. A static because the
229
+ * binding lives in a private field that only this class can read; used
230
+ * by {@link QURLClient.createPortal} to refuse handles bound to a
231
+ * different client.
232
+ */
233
+ static isBoundTo(resource, client) {
234
+ return resource.#client === client;
235
+ }
236
+ /**
237
+ * Mint a short-lived qURL link (a portal) for this resource. See
238
+ * {@link QURLClient.createPortal} for the option reference.
239
+ */
240
+ async createPortal(opts = {}, requestOptions) {
241
+ return this.#client.createPortal(this, opts, requestOptions);
242
+ }
243
+ }
244
+ exports.ProtectedResource = ProtectedResource;
@@ -0,0 +1,29 @@
1
+ import type { ConsumerAccessPolicy, CreateInput, CreateQurlForResourceInput, UpdateResourceQurlInput } from "./types.js";
2
+ export declare function validateCreateInput(input: CreateInput): void;
3
+ export declare function validateQurlTokenOptions(input: CreateQurlForResourceInput | undefined): void;
4
+ export declare function validateResourceQurlUpdateInput(input: UpdateResourceQurlInput): void;
5
+ export declare function validateResourceWriteFields(input: Record<string, unknown>, options?: {
6
+ allowAliasClear?: boolean;
7
+ allowCustomDomainClear?: boolean;
8
+ requireUrlTarget?: boolean;
9
+ validateFindOrCreate?: boolean;
10
+ validatePreserveHost?: boolean;
11
+ }): void;
12
+ /**
13
+ * Per-entry shape guard for {@link BatchItemResult}. Verifies every
14
+ * non-optional field on the branch of the discriminated union selected
15
+ * by the `success` discriminant. Protects consumers who narrow on
16
+ * `success` and then access `resource_id` / `qurl_link` / `error` as
17
+ * guaranteed-present — if the API ever omits one, we trip the guard
18
+ * rather than returning `undefined` where the type says `string`.
19
+ *
20
+ * Returns `null` when the entry is valid, or a human-readable reason
21
+ * string describing the *specific* field that's missing or wrong. The
22
+ * reason never echoes the entry's values — only field names and shape
23
+ * descriptors — so the caller can safely surface it in error messages
24
+ * that may end up in observability pipelines. Contrast with the outer
25
+ * guard's intentional silence about response-body content for the
26
+ * same info-leak reason.
27
+ */
28
+ export declare function batchItemResultValidationReason(entry: unknown): string | null;
29
+ export declare function sameConsumerPolicy(actual: ConsumerAccessPolicy | undefined, expected: ConsumerAccessPolicy, foundExisting: boolean): boolean;