@voyant-travel/apps 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/dist/contracts.d.ts +8 -87
- package/dist/contracts.js +0 -50
- package/dist/index.d.ts +1 -5
- package/dist/index.js +1 -5
- package/dist/installation-reconciliation.d.ts +1 -1
- package/dist/installation-reconciliation.js +1 -5
- package/dist/installation-service.d.ts +14 -25
- package/dist/installation-service.js +7 -22
- package/dist/routes.d.ts +1 -8
- package/dist/routes.js +1 -67
- package/dist/schema.d.ts +4 -536
- package/dist/schema.js +1 -52
- package/dist/service.d.ts +18 -18
- package/migrations/meta/_journal.json +0 -7
- package/package.json +78 -116
- package/dist/access-boundary.d.ts +0 -29
- package/dist/access-boundary.js +0 -33
- package/dist/app-api-contracts.d.ts +0 -51
- package/dist/app-api-contracts.js +0 -50
- package/dist/app-api-routes.d.ts +0 -26
- package/dist/app-api-routes.js +0 -133
- package/dist/app-api-service.d.ts +0 -1263
- package/dist/app-api-service.js +0 -231
- package/dist/app-api-service.test.d.ts +0 -1
- package/dist/app-api-service.test.js +0 -105
- package/dist/consent.d.ts +0 -15
- package/dist/consent.js +0 -50
- package/dist/consent.test.d.ts +0 -1
- package/dist/consent.test.js +0 -80
- package/dist/oauth-crypto.d.ts +0 -8
- package/dist/oauth-crypto.js +0 -23
- package/dist/oauth-crypto.test.d.ts +0 -1
- package/dist/oauth-crypto.test.js +0 -11
- package/dist/oauth-service.d.ts +0 -65
- package/dist/oauth-service.js +0 -381
- package/dist/oauth-service.test.d.ts +0 -1
- package/dist/oauth-service.test.js +0 -8
- package/migrations/20260717143000_app_oauth_authorization.sql +0 -47
package/dist/app-api-service.js
DELETED
|
@@ -1,231 +0,0 @@
|
|
|
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
|
-
const installation = await assertActiveAppInstallationAccess(db, {
|
|
137
|
-
installationId: context.installationId,
|
|
138
|
-
requiredScopes,
|
|
139
|
-
});
|
|
140
|
-
if (installation.appId !== context.appId || installation.releaseId !== context.releaseId) {
|
|
141
|
-
throw new ApiHttpError("App token does not match the active installation.", {
|
|
142
|
-
status: 403,
|
|
143
|
-
code: "app_api_token_installation_mismatch",
|
|
144
|
-
});
|
|
145
|
-
}
|
|
146
|
-
const [release] = await db
|
|
147
|
-
.select()
|
|
148
|
-
.from(appReleases)
|
|
149
|
-
.where(eq(appReleases.id, installation.releaseId))
|
|
150
|
-
.limit(1);
|
|
151
|
-
if (!release)
|
|
152
|
-
throw notFound("Installed app release not found.");
|
|
153
|
-
assertCompatibleVersion(context.apiVersion ?? APP_API_VERSION, release.apiCompatibility);
|
|
154
|
-
return { installation, release };
|
|
155
|
-
}
|
|
156
|
-
function enforceRateLimit(context) {
|
|
157
|
-
const policy = options.rateLimit ?? DEFAULT_RATE_LIMIT;
|
|
158
|
-
hit(`installation:${context.installationId}`, policy.installationLimit, policy.windowMs);
|
|
159
|
-
hit(`app:${context.appId}`, policy.appLimit, policy.windowMs);
|
|
160
|
-
}
|
|
161
|
-
function hit(key, limit, windowMs) {
|
|
162
|
-
const timestamp = now().getTime();
|
|
163
|
-
const bucket = buckets.get(key);
|
|
164
|
-
if (!bucket || bucket.resetAt <= timestamp) {
|
|
165
|
-
buckets.set(key, { count: 1, resetAt: timestamp + windowMs });
|
|
166
|
-
return;
|
|
167
|
-
}
|
|
168
|
-
if (bucket.count >= limit) {
|
|
169
|
-
throw new ApiHttpError("App API rate limit exceeded.", {
|
|
170
|
-
status: 429,
|
|
171
|
-
code: "app_api_rate_limited",
|
|
172
|
-
details: { key, resetAt: new Date(bucket.resetAt).toISOString() },
|
|
173
|
-
});
|
|
174
|
-
}
|
|
175
|
-
bucket.count += 1;
|
|
176
|
-
}
|
|
177
|
-
function owner(access) {
|
|
178
|
-
return createAppCustomFieldDefinitionOwner({
|
|
179
|
-
appId: access.installation.appId,
|
|
180
|
-
namespace: access.installation.namespace,
|
|
181
|
-
});
|
|
182
|
-
}
|
|
183
|
-
function customFieldsRequired() {
|
|
184
|
-
if (!customFields)
|
|
185
|
-
throw notSupported("Custom fields App API runtime is not configured.");
|
|
186
|
-
return customFields;
|
|
187
|
-
}
|
|
188
|
-
}
|
|
189
|
-
export function assertAppNamespaceAlias(namespace) {
|
|
190
|
-
if (!namespace || namespace === "$app")
|
|
191
|
-
return;
|
|
192
|
-
if (PHYSICAL_APP_NAMESPACE.test(namespace) || !REMOTE_APP_NAMESPACE.test(namespace)) {
|
|
193
|
-
throw new ApiHttpError("App APIs accept only the server-resolved $app namespace alias.", {
|
|
194
|
-
status: 400,
|
|
195
|
-
code: "app_api_invalid_custom_field_namespace",
|
|
196
|
-
});
|
|
197
|
-
}
|
|
198
|
-
}
|
|
199
|
-
export function assertCompatibleVersion(requested, range) {
|
|
200
|
-
if (requested < range.min || requested > range.max) {
|
|
201
|
-
throw new ApiHttpError("Requested App API version is outside the installed release range.", {
|
|
202
|
-
status: 426,
|
|
203
|
-
code: "app_api_version_out_of_range",
|
|
204
|
-
details: { requested, supported: range },
|
|
205
|
-
});
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
|
-
export async function withAppApiDeadline(promise, timeoutMs = 5_000) {
|
|
209
|
-
let timeout;
|
|
210
|
-
try {
|
|
211
|
-
return await Promise.race([
|
|
212
|
-
promise,
|
|
213
|
-
new Promise((_, reject) => {
|
|
214
|
-
timeout = setTimeout(() => reject(new ApiHttpError("App API request deadline exceeded.", {
|
|
215
|
-
status: 504,
|
|
216
|
-
code: "app_api_deadline_exceeded",
|
|
217
|
-
})), timeoutMs);
|
|
218
|
-
}),
|
|
219
|
-
]);
|
|
220
|
-
}
|
|
221
|
-
finally {
|
|
222
|
-
if (timeout)
|
|
223
|
-
clearTimeout(timeout);
|
|
224
|
-
}
|
|
225
|
-
}
|
|
226
|
-
function notSupported(message) {
|
|
227
|
-
return new ApiHttpError(message, { status: 501, code: "app_api_not_configured" });
|
|
228
|
-
}
|
|
229
|
-
function notFound(message) {
|
|
230
|
-
return new ApiHttpError(message, { status: 404, code: "not_found" });
|
|
231
|
-
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
|
@@ -1,105 +0,0 @@
|
|
|
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, ["app-installation:read"])).rejects.toMatchObject({ status: 403, code: "app_installation_not_active" });
|
|
61
|
-
});
|
|
62
|
-
it("rejects direct service calls when required scopes are not granted", async () => {
|
|
63
|
-
const service = createAppApiService();
|
|
64
|
-
await expect(service.requireAccess(createAccessDb({ scopes: [] }), context, ["app-installation:read"])).rejects.toMatchObject({ status: 403, code: "app_installation_scope_missing" });
|
|
65
|
-
});
|
|
66
|
-
it("fails closed when the requested API version is outside the installed release range", async () => {
|
|
67
|
-
const service = createAppApiService();
|
|
68
|
-
await expect(service.requireAccess(createAccessDb({
|
|
69
|
-
scopes: ["app-installation:read"],
|
|
70
|
-
releaseRange: { min: "2026-08-01", max: "2026-12-31" },
|
|
71
|
-
}), context, ["app-installation:read"])).rejects.toMatchObject({ status: 426, code: "app_api_version_out_of_range" });
|
|
72
|
-
});
|
|
73
|
-
it("requires action-ledger approval for finance actions even when OAuth scope is granted", async () => {
|
|
74
|
-
const executeAction = vi.fn();
|
|
75
|
-
const service = createAppApiService({
|
|
76
|
-
finance: { listDocuments: vi.fn(), executeAction },
|
|
77
|
-
});
|
|
78
|
-
await expect(service.executeFinanceAction(createAccessDb({ scopes: ["finance-actions:issue"] }), context, {
|
|
79
|
-
action: "issue",
|
|
80
|
-
idempotencyKey: "idem_1",
|
|
81
|
-
payload: {},
|
|
82
|
-
})).rejects.toMatchObject({ status: 403, code: "app_api_finance_approval_required" });
|
|
83
|
-
expect(executeAction).not.toHaveBeenCalled();
|
|
84
|
-
});
|
|
85
|
-
it("isolates rate limits per installation", async () => {
|
|
86
|
-
const service = createAppApiService({
|
|
87
|
-
rateLimit: { installationLimit: 1, appLimit: 10, windowMs: 60_000 },
|
|
88
|
-
});
|
|
89
|
-
const rateContext = { ...context, appId: "rate_app", installationId: "rate_inst_1" };
|
|
90
|
-
service.enforceRateLimit(rateContext);
|
|
91
|
-
expect(() => service.enforceRateLimit(rateContext)).toThrow(ApiHttpError);
|
|
92
|
-
expect(() => service.enforceRateLimit({ ...rateContext, installationId: "rate_inst_2" })).not.toThrow();
|
|
93
|
-
});
|
|
94
|
-
it("accepts only the $app custom-field namespace alias from request data", () => {
|
|
95
|
-
expect(() => assertAppNamespaceAlias(undefined)).not.toThrow();
|
|
96
|
-
expect(() => assertAppNamespaceAlias("$app")).not.toThrow();
|
|
97
|
-
expect(() => assertAppNamespaceAlias("$app:sync")).not.toThrow();
|
|
98
|
-
expect(() => assertAppNamespaceAlias("app--foreign")).toThrow(ApiHttpError);
|
|
99
|
-
expect(() => assertAppNamespaceAlias("custom")).toThrow(ApiHttpError);
|
|
100
|
-
});
|
|
101
|
-
it("compares App API compatibility ranges inclusively", () => {
|
|
102
|
-
expect(() => assertCompatibleVersion("2026-07-01", { min: "2026-07-01", max: "2026-12-31" })).not.toThrow();
|
|
103
|
-
expect(() => assertCompatibleVersion("2027-01-01", { min: "2026-07-01", max: "2026-12-31" })).toThrow(ApiHttpError);
|
|
104
|
-
});
|
|
105
|
-
});
|
package/dist/consent.d.ts
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
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;
|
package/dist/consent.js
DELETED
|
@@ -1,50 +0,0 @@
|
|
|
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 presetScopes = catalog.presets
|
|
33
|
-
.filter((preset) => preset.kind === "api-token-grant" && Boolean(preset.audience))
|
|
34
|
-
.flatMap((preset) => preset.grants);
|
|
35
|
-
return new Set(presetScopes.filter((scope) => catalogScopes.has(scope)));
|
|
36
|
-
}
|
|
37
|
-
function parseReleaseScopes(value) {
|
|
38
|
-
if (!value || typeof value !== "object")
|
|
39
|
-
return { requestedScopes: [], optionalScopes: [] };
|
|
40
|
-
const record = value;
|
|
41
|
-
return {
|
|
42
|
-
requestedScopes: stringArray(record.requestedScopes),
|
|
43
|
-
optionalScopes: stringArray(record.optionalScopes),
|
|
44
|
-
};
|
|
45
|
-
}
|
|
46
|
-
function stringArray(value) {
|
|
47
|
-
return Array.isArray(value)
|
|
48
|
-
? Array.from(new Set(value.filter((item) => typeof item === "string"))).sort()
|
|
49
|
-
: [];
|
|
50
|
-
}
|
package/dist/consent.test.d.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
package/dist/consent.test.js
DELETED
|
@@ -1,80 +0,0 @@
|
|
|
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
|
-
});
|
package/dist/oauth-crypto.d.ts
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
export declare const APP_ACCESS_TOKEN_PREFIX = "vapp_";
|
|
2
|
-
export declare const APP_REFRESH_TOKEN_PREFIX = "vappr_";
|
|
3
|
-
export declare const APP_AUTH_CODE_PREFIX = "vappc_";
|
|
4
|
-
export declare function randomToken(prefix: string, bytes?: number): string;
|
|
5
|
-
export declare function sha256Hex(value: string): string;
|
|
6
|
-
export declare function sha256Base64Url(value: string): string;
|
|
7
|
-
export declare function constantTimeEqual(left: string, right: string): boolean;
|
|
8
|
-
export declare function verifyPkceS256(verifier: string, challenge: string): boolean;
|
package/dist/oauth-crypto.js
DELETED
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
|
-
export const APP_ACCESS_TOKEN_PREFIX = "vapp_";
|
|
3
|
-
export const APP_REFRESH_TOKEN_PREFIX = "vappr_";
|
|
4
|
-
export const APP_AUTH_CODE_PREFIX = "vappc_";
|
|
5
|
-
export function randomToken(prefix, bytes = 32) {
|
|
6
|
-
return `${prefix}${randomBytes(bytes).toString("base64url")}`;
|
|
7
|
-
}
|
|
8
|
-
export function sha256Hex(value) {
|
|
9
|
-
return createHash("sha256").update(value).digest("hex");
|
|
10
|
-
}
|
|
11
|
-
export function sha256Base64Url(value) {
|
|
12
|
-
return createHash("sha256").update(value).digest("base64url");
|
|
13
|
-
}
|
|
14
|
-
export function constantTimeEqual(left, right) {
|
|
15
|
-
const leftHash = Buffer.from(sha256Hex(left), "hex");
|
|
16
|
-
const rightHash = Buffer.from(sha256Hex(right), "hex");
|
|
17
|
-
return timingSafeEqual(leftHash, rightHash);
|
|
18
|
-
}
|
|
19
|
-
export function verifyPkceS256(verifier, challenge) {
|
|
20
|
-
if (!/^[A-Za-z0-9._~-]{43,128}$/.test(verifier))
|
|
21
|
-
return false;
|
|
22
|
-
return constantTimeEqual(sha256Base64Url(verifier), challenge);
|
|
23
|
-
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from "vitest";
|
|
2
|
-
import { sha256Base64Url, verifyPkceS256 } from "./oauth-crypto.js";
|
|
3
|
-
describe("app OAuth PKCE", () => {
|
|
4
|
-
it("accepts only S256 challenges derived from the verifier", () => {
|
|
5
|
-
const verifier = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQ_0123456789-1234567890";
|
|
6
|
-
const challenge = sha256Base64Url(verifier);
|
|
7
|
-
expect(verifyPkceS256(verifier, challenge)).toBe(true);
|
|
8
|
-
expect(verifyPkceS256(`${verifier}x`, challenge)).toBe(false);
|
|
9
|
-
expect(verifyPkceS256("too-short", challenge)).toBe(false);
|
|
10
|
-
});
|
|
11
|
-
});
|
package/dist/oauth-service.d.ts
DELETED
|
@@ -1,65 +0,0 @@
|
|
|
1
|
-
import type { VoyantAuthContext } from "@voyant-travel/core";
|
|
2
|
-
import type { AccessCatalog } from "@voyant-travel/types/api-keys";
|
|
3
|
-
import type { PostgresJsDatabase } from "drizzle-orm/postgres-js";
|
|
4
|
-
export interface AppOAuthServiceOptions {
|
|
5
|
-
accessCatalog: AccessCatalog;
|
|
6
|
-
deploymentId: string;
|
|
7
|
-
now?: () => Date;
|
|
8
|
-
}
|
|
9
|
-
export interface AuthorizeAppInput {
|
|
10
|
-
appId: string;
|
|
11
|
-
releaseId: string;
|
|
12
|
-
redirectUri: string;
|
|
13
|
-
state: string;
|
|
14
|
-
codeChallenge: string;
|
|
15
|
-
codeChallengeMethod: "S256";
|
|
16
|
-
actorId: string;
|
|
17
|
-
operatorGrantedScopes: readonly string[];
|
|
18
|
-
grantedOptionalScopes?: readonly string[];
|
|
19
|
-
}
|
|
20
|
-
export interface TokenCodeInput {
|
|
21
|
-
grantType: "authorization_code";
|
|
22
|
-
code: string;
|
|
23
|
-
redirectUri: string;
|
|
24
|
-
codeVerifier: string;
|
|
25
|
-
clientId: string;
|
|
26
|
-
clientSecret?: string;
|
|
27
|
-
}
|
|
28
|
-
export interface RefreshTokenInput {
|
|
29
|
-
grantType: "refresh_token";
|
|
30
|
-
refreshToken: string;
|
|
31
|
-
clientId: string;
|
|
32
|
-
clientSecret?: string;
|
|
33
|
-
}
|
|
34
|
-
export interface TokenExchangeInput {
|
|
35
|
-
grantType: "urn:voyant:params:oauth:grant-type:actor-token-exchange";
|
|
36
|
-
installationId: string;
|
|
37
|
-
viewerId: string;
|
|
38
|
-
viewerScopes: readonly string[];
|
|
39
|
-
contextualScopes?: readonly string[];
|
|
40
|
-
clientId: string;
|
|
41
|
-
clientSecret?: string;
|
|
42
|
-
}
|
|
43
|
-
export type AppTokenInput = TokenCodeInput | RefreshTokenInput | TokenExchangeInput;
|
|
44
|
-
export declare function createAppOAuthService(options: AppOAuthServiceOptions): {
|
|
45
|
-
authorize: (db: PostgresJsDatabase, input: AuthorizeAppInput) => Promise<{
|
|
46
|
-
code: string;
|
|
47
|
-
state: string;
|
|
48
|
-
redirectUri: string;
|
|
49
|
-
expiresAt: Date;
|
|
50
|
-
}>;
|
|
51
|
-
token: (db: PostgresJsDatabase, input: AppTokenInput) => Promise<{
|
|
52
|
-
refreshToken?: string | undefined;
|
|
53
|
-
accessToken: string;
|
|
54
|
-
tokenType: "Bearer";
|
|
55
|
-
expiresIn: number;
|
|
56
|
-
scope: string;
|
|
57
|
-
tokenMode: "offline" | "online";
|
|
58
|
-
}>;
|
|
59
|
-
resolveAccessToken: (db: PostgresJsDatabase, rawToken: string) => Promise<VoyantAuthContext | null>;
|
|
60
|
-
revokeInstallationCredentials: (db: PostgresJsDatabase, installationId: string, actorId: string) => Promise<{
|
|
61
|
-
installationId: string;
|
|
62
|
-
generation: number;
|
|
63
|
-
}>;
|
|
64
|
-
};
|
|
65
|
-
export declare function intersectAppTokenScopes(...sets: readonly (readonly string[])[]): string[];
|