@voyant-travel/apps 0.2.0 → 0.4.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 (41) hide show
  1. package/dist/access-boundary.d.ts +29 -0
  2. package/dist/access-boundary.js +33 -0
  3. package/dist/api-runtime.d.ts +15 -0
  4. package/dist/api-runtime.js +15 -1
  5. package/dist/app-api-contracts.d.ts +51 -0
  6. package/dist/app-api-contracts.js +50 -0
  7. package/dist/app-api-routes.d.ts +28 -0
  8. package/dist/app-api-routes.js +141 -0
  9. package/dist/app-api-service.d.ts +1263 -0
  10. package/dist/app-api-service.js +244 -0
  11. package/dist/app-api-service.test.d.ts +1 -0
  12. package/dist/app-api-service.test.js +109 -0
  13. package/dist/consent.d.ts +15 -0
  14. package/dist/consent.js +65 -0
  15. package/dist/consent.test.d.ts +1 -0
  16. package/dist/consent.test.js +104 -0
  17. package/dist/contracts.d.ts +82 -3
  18. package/dist/contracts.js +50 -0
  19. package/dist/index.d.ts +8 -1
  20. package/dist/index.js +8 -1
  21. package/dist/installation-reconciliation.d.ts +1 -1
  22. package/dist/installation-reconciliation.js +5 -1
  23. package/dist/installation-service.d.ts +13 -2
  24. package/dist/installation-service.js +22 -7
  25. package/dist/oauth-crypto.d.ts +8 -0
  26. package/dist/oauth-crypto.js +23 -0
  27. package/dist/oauth-crypto.test.d.ts +1 -0
  28. package/dist/oauth-crypto.test.js +11 -0
  29. package/dist/oauth-service.d.ts +66 -0
  30. package/dist/oauth-service.js +398 -0
  31. package/dist/oauth-service.test.d.ts +1 -0
  32. package/dist/oauth-service.test.js +60 -0
  33. package/dist/routes.d.ts +8 -1
  34. package/dist/routes.js +70 -1
  35. package/dist/schema.d.ts +536 -4
  36. package/dist/schema.js +52 -1
  37. package/dist/service.d.ts +16 -16
  38. package/dist/voyant.js +87 -1
  39. package/migrations/20260717143000_app_oauth_authorization.sql +47 -0
  40. package/migrations/meta/_journal.json +7 -0
  41. package/package.json +40 -4
@@ -0,0 +1,244 @@
1
+ import { createAppCustomFieldDefinitionOwner, createCustomFieldsService, } from "@voyant-travel/custom-fields";
2
+ import { ApiHttpError } from "@voyant-travel/hono";
3
+ import { and, asc, eq, sql } from "drizzle-orm";
4
+ import { assertActiveAppInstallationAccess } from "./access-boundary.js";
5
+ import { APP_API_VERSION } from "./app-api-contracts.js";
6
+ import { appAuditEvents, appGrants, appReleases, appWebhookSubscriptions } from "./schema.js";
7
+ const DEFAULT_RATE_LIMIT = { installationLimit: 120, appLimit: 600, windowMs: 60_000 };
8
+ const REMOTE_APP_NAMESPACE = /^\$app(?::[a-z][a-z0-9-]*)?$/;
9
+ const PHYSICAL_APP_NAMESPACE = /^app--/;
10
+ const buckets = new Map();
11
+ export function createAppApiService(options = {}) {
12
+ const now = () => options.now?.() ?? new Date();
13
+ const customFields = options.customFieldTargets &&
14
+ createCustomFieldsService(options.customFieldTargets, options.customFieldValueLifecycles ?? [], options.customFieldValueOperations ?? []);
15
+ async function introspect(db, context) {
16
+ const access = await requireAccess(db, context, ["app-installation:read"]);
17
+ const grants = await db
18
+ .select({
19
+ scope: appGrants.scope,
20
+ status: appGrants.status,
21
+ optional: appGrants.optional,
22
+ })
23
+ .from(appGrants)
24
+ .where(eq(appGrants.installationId, context.installationId))
25
+ .orderBy(appGrants.scope);
26
+ return {
27
+ data: {
28
+ installation: {
29
+ id: access.installation.id,
30
+ appId: access.installation.appId,
31
+ status: access.installation.status,
32
+ namespace: access.installation.namespace,
33
+ deploymentId: access.installation.deploymentId,
34
+ },
35
+ release: {
36
+ id: access.release.id,
37
+ version: access.release.releaseVersion,
38
+ apiCompatibility: access.release.apiCompatibility,
39
+ },
40
+ grants,
41
+ },
42
+ };
43
+ }
44
+ async function listEntities(db, context, entity, query) {
45
+ await requireAccess(db, context, [`${entity}:read`]);
46
+ const reader = options.entityReaders?.[entity];
47
+ if (!reader)
48
+ throw notSupported(`Entity "${entity}" is not supported by the App API.`);
49
+ return { data: await reader.list(db, query) };
50
+ }
51
+ async function listFinanceDocuments(db, context, query) {
52
+ await requireAccess(db, context, ["finance-documents:read"]);
53
+ if (!options.finance)
54
+ throw notSupported("Finance App API runtime is not configured.");
55
+ return { data: await options.finance.listDocuments(db, query) };
56
+ }
57
+ async function executeFinanceAction(db, context, input) {
58
+ await requireAccess(db, context, [`finance-actions:${input.action}`]);
59
+ if (!options.finance)
60
+ throw notSupported("Finance App API runtime is not configured.");
61
+ if (!input.approvalId) {
62
+ throw new ApiHttpError("Finance action requires action-ledger approval.", {
63
+ status: 403,
64
+ code: "app_api_finance_approval_required",
65
+ });
66
+ }
67
+ return { data: await options.finance.executeAction(db, input) };
68
+ }
69
+ async function listCustomFieldDefinitions(db, context, query) {
70
+ const access = await requireAccess(db, context, ["custom-field-definitions:read"]);
71
+ return customFieldsRequired().listForOwner(db, owner(access), query);
72
+ }
73
+ async function createCustomFieldDefinition(db, context, namespace, input) {
74
+ assertAppNamespaceAlias(namespace);
75
+ const access = await requireAccess(db, context, ["custom-field-definitions:write"]);
76
+ return { data: await customFieldsRequired().createForOwner(db, owner(access), input) };
77
+ }
78
+ async function updateCustomFieldDefinition(db, context, id, namespace, input) {
79
+ assertAppNamespaceAlias(namespace);
80
+ const access = await requireAccess(db, context, ["custom-field-definitions:write"]);
81
+ const data = await customFieldsRequired().updateForOwner(db, owner(access), id, input);
82
+ if (!data)
83
+ throw notFound("Custom-field definition not found.");
84
+ return { data };
85
+ }
86
+ async function listCustomFieldValues(db, context, query) {
87
+ await requireAccess(db, context, [`custom-field-values:${query.entityType ?? "read"}`]);
88
+ const access = await requireAccess(db, context, ["custom-field-values:read"]);
89
+ return customFieldsRequired().values.listForOwner(db, owner(access), query);
90
+ }
91
+ async function upsertCustomFieldValue(db, context, definitionId, input) {
92
+ await requireAccess(db, context, [
93
+ "custom-field-values:write",
94
+ `custom-field-values:${input.entityType}`,
95
+ ]);
96
+ const access = await requireAccess(db, context, []);
97
+ return {
98
+ data: await customFieldsRequired().values.upsertForOwner(db, owner(access), definitionId, input),
99
+ };
100
+ }
101
+ async function listWebhookHealth(db, context) {
102
+ await requireAccess(db, context, ["webhooks:read"]);
103
+ const data = await db
104
+ .select()
105
+ .from(appWebhookSubscriptions)
106
+ .where(eq(appWebhookSubscriptions.installationId, context.installationId))
107
+ .orderBy(asc(appWebhookSubscriptions.eventType));
108
+ return { data };
109
+ }
110
+ async function listAuditHistory(db, context, query) {
111
+ await requireAccess(db, context, ["app-audit:read"]);
112
+ const where = and(eq(appAuditEvents.appId, context.appId), eq(appAuditEvents.installationId, context.installationId));
113
+ const [data, count] = await Promise.all([
114
+ db.select().from(appAuditEvents).where(where).limit(query.limit).offset(query.offset),
115
+ db.select({ count: sql `count(*)::int` }).from(appAuditEvents).where(where),
116
+ ]);
117
+ return { data, total: count[0]?.count ?? 0, limit: query.limit, offset: query.offset };
118
+ }
119
+ return {
120
+ introspect,
121
+ listEntities,
122
+ listFinanceDocuments,
123
+ executeFinanceAction,
124
+ listCustomFieldDefinitions,
125
+ createCustomFieldDefinition,
126
+ updateCustomFieldDefinition,
127
+ listCustomFieldValues,
128
+ upsertCustomFieldValue,
129
+ listWebhookHealth,
130
+ listAuditHistory,
131
+ requireAccess,
132
+ enforceRateLimit,
133
+ };
134
+ async function requireAccess(db, context, requiredScopes) {
135
+ enforceRateLimit(context);
136
+ // The token's own scopes are the authority: for online tokens this is the
137
+ // narrowed viewer/context intersection minted at exchange, so an endpoint
138
+ // must not be reachable just because the installation was granted its
139
+ // scope. The installation-grant check below stays as defense in depth.
140
+ const tokenScopes = new Set(context.scopes);
141
+ const missingFromToken = requiredScopes.filter((scope) => !tokenScopes.has(scope));
142
+ if (missingFromToken.length > 0) {
143
+ throw new ApiHttpError("App token is missing required scopes", {
144
+ status: 403,
145
+ code: "app_api_token_scope_missing",
146
+ details: { scopes: [...missingFromToken].sort() },
147
+ });
148
+ }
149
+ const installation = await assertActiveAppInstallationAccess(db, {
150
+ installationId: context.installationId,
151
+ requiredScopes,
152
+ });
153
+ if (installation.appId !== context.appId || installation.releaseId !== context.releaseId) {
154
+ throw new ApiHttpError("App token does not match the active installation.", {
155
+ status: 403,
156
+ code: "app_api_token_installation_mismatch",
157
+ });
158
+ }
159
+ const [release] = await db
160
+ .select()
161
+ .from(appReleases)
162
+ .where(eq(appReleases.id, installation.releaseId))
163
+ .limit(1);
164
+ if (!release)
165
+ throw notFound("Installed app release not found.");
166
+ assertCompatibleVersion(context.apiVersion ?? APP_API_VERSION, release.apiCompatibility);
167
+ return { installation, release };
168
+ }
169
+ function enforceRateLimit(context) {
170
+ const policy = options.rateLimit ?? DEFAULT_RATE_LIMIT;
171
+ hit(`installation:${context.installationId}`, policy.installationLimit, policy.windowMs);
172
+ hit(`app:${context.appId}`, policy.appLimit, policy.windowMs);
173
+ }
174
+ function hit(key, limit, windowMs) {
175
+ const timestamp = now().getTime();
176
+ const bucket = buckets.get(key);
177
+ if (!bucket || bucket.resetAt <= timestamp) {
178
+ buckets.set(key, { count: 1, resetAt: timestamp + windowMs });
179
+ return;
180
+ }
181
+ if (bucket.count >= limit) {
182
+ throw new ApiHttpError("App API rate limit exceeded.", {
183
+ status: 429,
184
+ code: "app_api_rate_limited",
185
+ details: { key, resetAt: new Date(bucket.resetAt).toISOString() },
186
+ });
187
+ }
188
+ bucket.count += 1;
189
+ }
190
+ function owner(access) {
191
+ return createAppCustomFieldDefinitionOwner({
192
+ appId: access.installation.appId,
193
+ namespace: access.installation.namespace,
194
+ });
195
+ }
196
+ function customFieldsRequired() {
197
+ if (!customFields)
198
+ throw notSupported("Custom fields App API runtime is not configured.");
199
+ return customFields;
200
+ }
201
+ }
202
+ export function assertAppNamespaceAlias(namespace) {
203
+ if (!namespace || namespace === "$app")
204
+ return;
205
+ if (PHYSICAL_APP_NAMESPACE.test(namespace) || !REMOTE_APP_NAMESPACE.test(namespace)) {
206
+ throw new ApiHttpError("App APIs accept only the server-resolved $app namespace alias.", {
207
+ status: 400,
208
+ code: "app_api_invalid_custom_field_namespace",
209
+ });
210
+ }
211
+ }
212
+ export function assertCompatibleVersion(requested, range) {
213
+ if (requested < range.min || requested > range.max) {
214
+ throw new ApiHttpError("Requested App API version is outside the installed release range.", {
215
+ status: 426,
216
+ code: "app_api_version_out_of_range",
217
+ details: { requested, supported: range },
218
+ });
219
+ }
220
+ }
221
+ export async function withAppApiDeadline(promise, timeoutMs = 5_000) {
222
+ let timeout;
223
+ try {
224
+ return await Promise.race([
225
+ promise,
226
+ new Promise((_, reject) => {
227
+ timeout = setTimeout(() => reject(new ApiHttpError("App API request deadline exceeded.", {
228
+ status: 504,
229
+ code: "app_api_deadline_exceeded",
230
+ })), timeoutMs);
231
+ }),
232
+ ]);
233
+ }
234
+ finally {
235
+ if (timeout)
236
+ clearTimeout(timeout);
237
+ }
238
+ }
239
+ function notSupported(message) {
240
+ return new ApiHttpError(message, { status: 501, code: "app_api_not_configured" });
241
+ }
242
+ function notFound(message) {
243
+ return new ApiHttpError(message, { status: 404, code: "not_found" });
244
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,109 @@
1
+ import { ApiHttpError } from "@voyant-travel/hono";
2
+ import { describe, expect, it, vi } from "vitest";
3
+ import { assertAppNamespaceAlias, assertCompatibleVersion, createAppApiService, } from "./app-api-service.js";
4
+ import { appGrants, appInstallations, appReleases } from "./schema.js";
5
+ function postgresStub(implementation) {
6
+ const db = Object.create(null);
7
+ Object.assign(db, implementation);
8
+ return db;
9
+ }
10
+ function createAccessDb(options) {
11
+ const installation = {
12
+ id: "inst_1",
13
+ appId: "app_1",
14
+ deploymentId: "dep_1",
15
+ releaseId: "rel_1",
16
+ status: options.status ?? "active",
17
+ namespace: "app--one",
18
+ };
19
+ const release = {
20
+ id: "rel_1",
21
+ appId: "app_1",
22
+ releaseVersion: "1.0.0",
23
+ apiCompatibility: options.releaseRange ?? { min: "2026-07-01", max: "2026-12-31" },
24
+ };
25
+ return postgresStub({
26
+ select: () => ({
27
+ from: (table) => ({
28
+ where: () => {
29
+ const rows = () => {
30
+ if (table === appInstallations)
31
+ return [installation];
32
+ if (table === appReleases)
33
+ return [release];
34
+ if (table === appGrants)
35
+ return (options.scopes ?? []).map((scope) => ({ scope }));
36
+ return [];
37
+ };
38
+ return {
39
+ // biome-ignore lint/suspicious/noThenProperty: test stub models Drizzle's awaitable query builder -- owner: apps.
40
+ then: (resolve) => Promise.resolve(rows()).then(resolve),
41
+ orderBy: async () => rows(),
42
+ limit: async () => rows(),
43
+ };
44
+ },
45
+ }),
46
+ }),
47
+ });
48
+ }
49
+ const context = {
50
+ appId: "app_1",
51
+ installationId: "inst_1",
52
+ releaseId: "rel_1",
53
+ tokenMode: "offline",
54
+ scopes: [],
55
+ apiVersion: "2026-07-01",
56
+ };
57
+ describe("App API service boundary", () => {
58
+ it("rejects direct service calls when the installation is inactive", async () => {
59
+ const service = createAppApiService();
60
+ await expect(service.requireAccess(createAccessDb({ status: "paused", scopes: ["app-installation:read"] }), { ...context, scopes: ["app-installation:read"] }, ["app-installation:read"])).rejects.toMatchObject({ status: 403, code: "app_installation_not_active" });
61
+ });
62
+ it("rejects when the installation grant is missing even if the token carries the scope", async () => {
63
+ const service = createAppApiService();
64
+ await expect(service.requireAccess(createAccessDb({ scopes: [] }), { ...context, scopes: ["app-installation:read"] }, ["app-installation:read"])).rejects.toMatchObject({ status: 403, code: "app_installation_scope_missing" });
65
+ });
66
+ it("rejects when a narrowed online token lacks the scope the installation was granted", async () => {
67
+ const service = createAppApiService();
68
+ await expect(service.requireAccess(createAccessDb({ scopes: ["app-installation:read", "finance-documents:read"] }), { ...context, tokenMode: "online", scopes: ["app-installation:read"] }, ["finance-documents:read"])).rejects.toMatchObject({ status: 403, code: "app_api_token_scope_missing" });
69
+ });
70
+ it("fails closed when the requested API version is outside the installed release range", async () => {
71
+ const service = createAppApiService();
72
+ await expect(service.requireAccess(createAccessDb({
73
+ scopes: ["app-installation:read"],
74
+ releaseRange: { min: "2026-08-01", max: "2026-12-31" },
75
+ }), { ...context, scopes: ["app-installation:read"] }, ["app-installation:read"])).rejects.toMatchObject({ status: 426, code: "app_api_version_out_of_range" });
76
+ });
77
+ it("requires action-ledger approval for finance actions even when OAuth scope is granted", async () => {
78
+ const executeAction = vi.fn();
79
+ const service = createAppApiService({
80
+ finance: { listDocuments: vi.fn(), executeAction },
81
+ });
82
+ await expect(service.executeFinanceAction(createAccessDb({ scopes: ["finance-actions:issue"] }), { ...context, scopes: ["finance-actions:issue"] }, {
83
+ action: "issue",
84
+ idempotencyKey: "idem_1",
85
+ payload: {},
86
+ })).rejects.toMatchObject({ status: 403, code: "app_api_finance_approval_required" });
87
+ expect(executeAction).not.toHaveBeenCalled();
88
+ });
89
+ it("isolates rate limits per installation", async () => {
90
+ const service = createAppApiService({
91
+ rateLimit: { installationLimit: 1, appLimit: 10, windowMs: 60_000 },
92
+ });
93
+ const rateContext = { ...context, appId: "rate_app", installationId: "rate_inst_1" };
94
+ service.enforceRateLimit(rateContext);
95
+ expect(() => service.enforceRateLimit(rateContext)).toThrow(ApiHttpError);
96
+ expect(() => service.enforceRateLimit({ ...rateContext, installationId: "rate_inst_2" })).not.toThrow();
97
+ });
98
+ it("accepts only the $app custom-field namespace alias from request data", () => {
99
+ expect(() => assertAppNamespaceAlias(undefined)).not.toThrow();
100
+ expect(() => assertAppNamespaceAlias("$app")).not.toThrow();
101
+ expect(() => assertAppNamespaceAlias("$app:sync")).not.toThrow();
102
+ expect(() => assertAppNamespaceAlias("app--foreign")).toThrow(ApiHttpError);
103
+ expect(() => assertAppNamespaceAlias("custom")).toThrow(ApiHttpError);
104
+ });
105
+ it("compares App API compatibility ranges inclusively", () => {
106
+ expect(() => assertCompatibleVersion("2026-07-01", { min: "2026-07-01", max: "2026-12-31" })).not.toThrow();
107
+ expect(() => assertCompatibleVersion("2027-01-01", { min: "2026-07-01", max: "2026-12-31" })).toThrow(ApiHttpError);
108
+ });
109
+ });
@@ -0,0 +1,15 @@
1
+ import type { AccessCatalog } from "@voyant-travel/types/api-keys";
2
+ import type { AppRelease } from "./schema.js";
3
+ export interface ConsentComputationInput {
4
+ release: AppRelease;
5
+ accessCatalog: AccessCatalog;
6
+ operatorGrantedScopes: readonly string[];
7
+ grantedOptionalScopes?: readonly string[];
8
+ }
9
+ export interface ComputedConsent {
10
+ requiredScopes: string[];
11
+ optionalScopes: string[];
12
+ grantedScopes: string[];
13
+ deniedOptionalScopes: string[];
14
+ }
15
+ export declare function computeAppConsent(input: ConsentComputationInput): ComputedConsent;
@@ -0,0 +1,65 @@
1
+ import { ApiHttpError } from "@voyant-travel/hono";
2
+ export function computeAppConsent(input) {
3
+ const normalized = parseReleaseScopes(input.release.normalizedRecord);
4
+ const remoteSafe = remoteSafeScopes(input.accessCatalog);
5
+ const operatorGranted = new Set(input.operatorGrantedScopes);
6
+ const optionalGrantRequest = new Set(input.grantedOptionalScopes ?? []);
7
+ const requiredScopes = normalized.requestedScopes.filter((scope) => canGrantScope(scope, remoteSafe, operatorGranted));
8
+ const missingRequired = normalized.requestedScopes.filter((scope) => !requiredScopes.includes(scope));
9
+ if (missingRequired.length > 0) {
10
+ throw new ApiHttpError("Required app scopes are not grantable for remote apps", {
11
+ status: 403,
12
+ code: "app_required_scope_not_grantable",
13
+ details: { scopes: missingRequired },
14
+ });
15
+ }
16
+ const optionalScopes = normalized.optionalScopes.filter((scope) => canGrantScope(scope, remoteSafe, operatorGranted));
17
+ const grantedOptional = optionalScopes.filter((scope) => optionalGrantRequest.has(scope));
18
+ const deniedOptionalScopes = normalized.optionalScopes.filter((scope) => !grantedOptional.includes(scope));
19
+ const grantedScopes = Array.from(new Set([...requiredScopes, ...grantedOptional])).sort();
20
+ return {
21
+ requiredScopes: requiredScopes.sort(),
22
+ optionalScopes: optionalScopes.sort(),
23
+ grantedScopes,
24
+ deniedOptionalScopes: deniedOptionalScopes.sort(),
25
+ };
26
+ }
27
+ function canGrantScope(scope, remoteSafe, operatorGranted) {
28
+ return remoteSafe.has(scope) && operatorGranted.has(scope);
29
+ }
30
+ function remoteSafeScopes(catalog) {
31
+ const catalogScopes = new Set(catalog.resources.flatMap((resource) => resource.actions.map((action) => `${resource.resource}:${action.action}`)));
32
+ const remoteSafe = new Set();
33
+ // A scope is remote-safe when its owning resource is flagged remoteSafe, or
34
+ // when the specific action is. This is the authority for App API scopes;
35
+ // audience presets remain supported for operator-declared grant bundles.
36
+ for (const resource of catalog.resources) {
37
+ for (const action of resource.actions) {
38
+ if (resource.remoteSafe || action.remoteSafe) {
39
+ remoteSafe.add(`${resource.resource}:${action.action}`);
40
+ }
41
+ }
42
+ }
43
+ const presetScopes = catalog.presets
44
+ .filter((preset) => preset.kind === "api-token-grant" && Boolean(preset.audience))
45
+ .flatMap((preset) => preset.grants);
46
+ for (const scope of presetScopes) {
47
+ if (catalogScopes.has(scope))
48
+ remoteSafe.add(scope);
49
+ }
50
+ return remoteSafe;
51
+ }
52
+ function parseReleaseScopes(value) {
53
+ if (!value || typeof value !== "object")
54
+ return { requestedScopes: [], optionalScopes: [] };
55
+ const record = value;
56
+ return {
57
+ requestedScopes: stringArray(record.requestedScopes),
58
+ optionalScopes: stringArray(record.optionalScopes),
59
+ };
60
+ }
61
+ function stringArray(value) {
62
+ return Array.isArray(value)
63
+ ? Array.from(new Set(value.filter((item) => typeof item === "string"))).sort()
64
+ : [];
65
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,104 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { computeAppConsent } from "./consent.js";
3
+ const catalog = {
4
+ resources: [
5
+ {
6
+ id: "bookings",
7
+ unitId: "bookings",
8
+ resource: "bookings",
9
+ label: "Bookings",
10
+ description: "Bookings",
11
+ wildcard: "allow",
12
+ actions: [{ action: "read", label: "Read", description: "Read" }],
13
+ },
14
+ {
15
+ id: "invoices",
16
+ unitId: "finance",
17
+ resource: "invoices",
18
+ label: "Invoices",
19
+ description: "Invoices",
20
+ wildcard: "allow",
21
+ actions: [{ action: "read", label: "Read", description: "Read" }],
22
+ },
23
+ ],
24
+ presets: [
25
+ {
26
+ id: "remote-safe",
27
+ kind: "api-token-grant",
28
+ audience: "staff",
29
+ label: "Remote safe",
30
+ description: "Remote app grants",
31
+ grants: ["bookings:read"],
32
+ },
33
+ ],
34
+ };
35
+ function release(requestedScopes, optionalScopes) {
36
+ return {
37
+ id: "release_1",
38
+ appId: "app_1",
39
+ releaseVersion: "1.0.0",
40
+ manifestSchemaVersion: "voyant.app-manifest.v1",
41
+ manifestDigest: "digest",
42
+ manifestSnapshot: {},
43
+ normalizedRecord: {
44
+ schemaVersion: "voyant.app-release.normalized.v1",
45
+ releaseVersion: "1.0.0",
46
+ digest: "digest",
47
+ requestedScopes,
48
+ optionalScopes,
49
+ adminPages: [],
50
+ slotExtensions: [],
51
+ webhooks: [],
52
+ customFields: [],
53
+ },
54
+ apiCompatibility: { min: "2026-01-01", max: "2026-12-31" },
55
+ defaultLocale: "en-US",
56
+ supportedLocales: ["en-US"],
57
+ state: "available",
58
+ createdBy: "user_1",
59
+ createdAt: new Date(),
60
+ };
61
+ }
62
+ describe("app OAuth consent computation", () => {
63
+ it("grants only scopes present in the catalog, remote-safe, and operator-granted", () => {
64
+ const consent = computeAppConsent({
65
+ release: release(["bookings:read"], ["invoices:read"]),
66
+ accessCatalog: catalog,
67
+ operatorGrantedScopes: ["bookings:read", "invoices:read"],
68
+ grantedOptionalScopes: ["invoices:read"],
69
+ });
70
+ expect(consent.grantedScopes).toEqual(["bookings:read"]);
71
+ expect(consent.deniedOptionalScopes).toEqual(["invoices:read"]);
72
+ });
73
+ it("rejects required scopes that are absent, unsafe, or not operator-granted", () => {
74
+ expect(() => computeAppConsent({
75
+ release: release(["invoices:read"], []),
76
+ accessCatalog: catalog,
77
+ operatorGrantedScopes: ["invoices:read"],
78
+ })).toThrow("Required app scopes are not grantable");
79
+ });
80
+ it("grants App API scopes marked remoteSafe on the resource without a matching preset", () => {
81
+ const withRemoteSafe = {
82
+ ...catalog,
83
+ resources: [
84
+ ...catalog.resources,
85
+ {
86
+ id: "app-installation",
87
+ unitId: "apps",
88
+ resource: "app-installation",
89
+ label: "App installation",
90
+ description: "Self",
91
+ wildcard: "explicit-resource",
92
+ remoteSafe: true,
93
+ actions: [{ action: "read", label: "Read", description: "Read" }],
94
+ },
95
+ ],
96
+ };
97
+ const consent = computeAppConsent({
98
+ release: release(["app-installation:read"], []),
99
+ accessCatalog: withRemoteSafe,
100
+ operatorGrantedScopes: ["app-installation:read"],
101
+ });
102
+ expect(consent.grantedScopes).toEqual(["app-installation:read"]);
103
+ });
104
+ });
@@ -29,8 +29,8 @@ export declare const appOwnedCustomFieldDeclarationSchema: z.ZodObject<{
29
29
  }, z.core.$strip>>>>;
30
30
  logicalNamespace: z.ZodOptional<z.ZodString>;
31
31
  dataClassification: z.ZodDefault<z.ZodEnum<{
32
- public: "public";
33
32
  internal: "internal";
33
+ public: "public";
34
34
  confidential: "confidential";
35
35
  restricted: "restricted";
36
36
  personal: "personal";
@@ -106,8 +106,8 @@ export declare const appManifestSchema: z.ZodPipe<z.ZodRecord<z.ZodString, z.Zod
106
106
  }, z.core.$strip>>>>;
107
107
  logicalNamespace: z.ZodOptional<z.ZodString>;
108
108
  dataClassification: z.ZodDefault<z.ZodEnum<{
109
- public: "public";
110
109
  internal: "internal";
110
+ public: "public";
111
111
  confidential: "confidential";
112
112
  restricted: "restricted";
113
113
  personal: "personal";
@@ -134,8 +134,8 @@ export declare const appManifestSchema: z.ZodPipe<z.ZodRecord<z.ZodString, z.Zod
134
134
  }, z.core.$strict>;
135
135
  data: z.ZodObject<{
136
136
  classifications: z.ZodArray<z.ZodEnum<{
137
- public: "public";
138
137
  internal: "internal";
138
+ public: "public";
139
139
  confidential: "confidential";
140
140
  restricted: "restricted";
141
141
  personal: "personal";
@@ -176,9 +176,88 @@ export declare const appWebhookReplaySchema: z.ZodObject<{
176
176
  signingKeyId: z.ZodString;
177
177
  signingSecret: z.ZodString;
178
178
  }, z.core.$strict>;
179
+ export declare const appOAuthAuthorizeQuerySchema: z.ZodObject<{
180
+ response_type: z.ZodLiteral<"code">;
181
+ client_id: z.ZodString;
182
+ release_id: z.ZodString;
183
+ redirect_uri: z.ZodString;
184
+ state: z.ZodString;
185
+ code_challenge: z.ZodString;
186
+ code_challenge_method: z.ZodLiteral<"S256">;
187
+ actor_id: z.ZodString;
188
+ operator_scopes: z.ZodDefault<z.ZodString>;
189
+ optional_scopes: z.ZodDefault<z.ZodString>;
190
+ }, z.core.$strict>;
191
+ export declare const appOAuthTokenSchema: z.ZodPipe<z.ZodDiscriminatedUnion<[z.ZodObject<{
192
+ grant_type: z.ZodLiteral<"authorization_code">;
193
+ code: z.ZodString;
194
+ redirect_uri: z.ZodString;
195
+ code_verifier: z.ZodString;
196
+ client_id: z.ZodString;
197
+ client_secret: z.ZodOptional<z.ZodString>;
198
+ }, z.core.$strip>, z.ZodObject<{
199
+ grant_type: z.ZodLiteral<"refresh_token">;
200
+ refresh_token: z.ZodString;
201
+ client_id: z.ZodString;
202
+ client_secret: z.ZodOptional<z.ZodString>;
203
+ }, z.core.$strip>, z.ZodObject<{
204
+ grant_type: z.ZodLiteral<"urn:voyant:params:oauth:grant-type:actor-token-exchange">;
205
+ installation_id: z.ZodString;
206
+ viewer_id: z.ZodString;
207
+ viewer_scopes: z.ZodDefault<z.ZodArray<z.ZodString>>;
208
+ contextual_scopes: z.ZodOptional<z.ZodArray<z.ZodString>>;
209
+ client_id: z.ZodString;
210
+ client_secret: z.ZodOptional<z.ZodString>;
211
+ }, z.core.$strip>], "grant_type">, z.ZodTransform<{
212
+ client_secret: string | undefined;
213
+ grant_type: "authorization_code";
214
+ code: string;
215
+ redirect_uri: string;
216
+ code_verifier: string;
217
+ client_id: string;
218
+ } | {
219
+ client_secret: string | undefined;
220
+ grant_type: "refresh_token";
221
+ refresh_token: string;
222
+ client_id: string;
223
+ } | {
224
+ client_secret: string | undefined;
225
+ grant_type: "urn:voyant:params:oauth:grant-type:actor-token-exchange";
226
+ installation_id: string;
227
+ viewer_id: string;
228
+ viewer_scopes: string[];
229
+ client_id: string;
230
+ contextual_scopes?: string[] | undefined;
231
+ }, {
232
+ grant_type: "authorization_code";
233
+ code: string;
234
+ redirect_uri: string;
235
+ code_verifier: string;
236
+ client_id: string;
237
+ client_secret?: string | undefined;
238
+ } | {
239
+ grant_type: "refresh_token";
240
+ refresh_token: string;
241
+ client_id: string;
242
+ client_secret?: string | undefined;
243
+ } | {
244
+ grant_type: "urn:voyant:params:oauth:grant-type:actor-token-exchange";
245
+ installation_id: string;
246
+ viewer_id: string;
247
+ viewer_scopes: string[];
248
+ client_id: string;
249
+ contextual_scopes?: string[] | undefined;
250
+ client_secret?: string | undefined;
251
+ }>>;
252
+ export declare const appCredentialRevocationSchema: z.ZodObject<{
253
+ installationId: z.ZodString;
254
+ actorId: z.ZodString;
255
+ }, z.core.$strict>;
179
256
  export type AppManifest = z.infer<typeof appManifestSchema>;
180
257
  export type CreateCustomAppRegistrationInput = z.infer<typeof createCustomAppRegistrationSchema>;
181
258
  export type ReleaseManifestUploadInput = z.infer<typeof releaseManifestUploadSchema>;
182
259
  export type ReleaseManifestFetchInput = z.infer<typeof releaseManifestFetchSchema>;
183
260
  export type AppListQuery = z.infer<typeof appListQuerySchema>;
184
261
  export type AppWebhookReplayInput = z.infer<typeof appWebhookReplaySchema>;
262
+ export type AppOAuthAuthorizeQuery = z.infer<typeof appOAuthAuthorizeQuerySchema>;
263
+ export type AppOAuthTokenInput = z.infer<typeof appOAuthTokenSchema>;