@jskit-ai/rewarded-core 0.2.3 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,6 @@
1
1
  import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
2
2
  import { normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
3
3
 
4
- const REWARDED_SURFACE = "app";
5
-
6
4
  const REWARDED_GATE_CONFIGURATION_REASONS = new Set([
7
5
  "rule-not-configured",
8
6
  "provider-not-configured"
@@ -42,56 +40,52 @@ const REWARDED_GATE_REASON_ERROR_MAP = Object.freeze({
42
40
  }
43
41
  });
44
42
 
45
- function normalizeReason(value = "") {
43
+ function normalizeReason(value) {
46
44
  return normalizeText(value).toLowerCase();
47
45
  }
48
46
 
49
- function isUnlockSatisfied(gateState = null) {
50
- const reason = normalizeReason(gateState?.reason);
51
- return Boolean(gateState?.unlock) || reason === "already-unlocked";
47
+ function isUnlockSatisfied(gateState) {
48
+ return Boolean(gateState.unlock) || normalizeReason(gateState.reason) === "already-unlocked";
52
49
  }
53
50
 
54
51
  function hasBooleanGateFlag(gateState, key) {
55
52
  return gateState && typeof gateState === "object" && typeof gateState[key] === "boolean";
56
53
  }
57
54
 
58
- function assertWellFormedGateState(gateState = null) {
55
+ /**
56
+ * Refuses a gate state that is not an object with boolean enabled and blocked
57
+ * flags and a blocking, unlocked or known non-blocking reason.
58
+ * @param {unknown} gateState What the Rewarded service answered.
59
+ */
60
+ function assertWellFormedGateState(gateState) {
59
61
  if (hasBooleanGateFlag(gateState, "enabled") && hasBooleanGateFlag(gateState, "blocked")) {
60
62
  if (
61
63
  gateState.blocked === true ||
62
64
  isUnlockSatisfied(gateState) ||
63
- REWARDED_GATE_NON_BLOCKING_REASONS.has(normalizeReason(gateState?.reason))
65
+ REWARDED_GATE_NON_BLOCKING_REASONS.has(normalizeReason(gateState.reason))
64
66
  ) {
65
67
  return;
66
68
  }
67
69
  }
68
70
 
69
- throw new AppError(503, "Rewarded gate returned an invalid state.", {
70
- code: "rewarded_gate_state_invalid",
71
- details: {
72
- rewardedGate: gateState
73
- }
74
- });
71
+ throw new Error("Rewarded gate returned an invalid state.");
75
72
  }
76
73
 
77
- function isConfigurationBypassAllowed(gateState = null, requireConfigured = false) {
74
+ function isConfigurationBypassAllowed(gateState, requireConfigured) {
78
75
  if (requireConfigured === true) {
79
76
  return false;
80
77
  }
81
78
 
82
- if (gateState?.enabled === true) {
79
+ if (gateState.enabled === true) {
83
80
  return false;
84
81
  }
85
82
 
86
- const reason = normalizeReason(gateState?.reason);
83
+ const reason = normalizeReason(gateState.reason);
87
84
  return REWARDED_GATE_CONFIGURATION_REASONS.has(reason) || !reason;
88
85
  }
89
86
 
90
- function createRewardedGateError(gateState = null, {
91
- errorCode = "",
92
- errorMessage = ""
93
- } = {}) {
94
- const reason = normalizeReason(gateState?.reason);
87
+ function buildRewardedGateError(gateState, { errorCode, errorMessage }) {
88
+ const reason = normalizeReason(gateState.reason);
95
89
  const defaults = REWARDED_GATE_REASON_ERROR_MAP[reason] || {
96
90
  status: 423,
97
91
  code: "rewarded_unlock_blocked",
@@ -106,32 +100,31 @@ function createRewardedGateError(gateState = null, {
106
100
  });
107
101
  }
108
102
 
103
+ /**
104
+ * Answers the gate's current state when it is unlocked (or, unless
105
+ * requireConfigured, not configured); otherwise throws the gate's error.
106
+ * @param {import("../types.js").RewardedCore} rewardedService
107
+ * @param {object} [input] The gate to check: its gateKey and workspaceSlug.
108
+ * @param {object} [options]
109
+ * @param {object | null} [options.context]
110
+ * @param {boolean} [options.requireConfigured]
111
+ * @param {string} [options.errorCode]
112
+ * @param {string} [options.errorMessage]
113
+ */
109
114
  async function requireRewardedUnlock(rewardedService, input = {}, {
110
115
  context = null,
111
116
  requireConfigured = false,
112
117
  errorCode = "",
113
118
  errorMessage = ""
114
119
  } = {}) {
115
- if (!rewardedService || typeof rewardedService.getCurrentState !== "function") {
116
- throw new TypeError("requireRewardedUnlock requires rewardedService.getCurrentState().");
117
- }
118
-
119
- const gateState = await rewardedService.getCurrentState(
120
- {
121
- ...input,
122
- surface: REWARDED_SURFACE
123
- },
124
- {
125
- context
126
- }
127
- );
120
+ const gateState = await rewardedService.getCurrentState(input, { context });
128
121
  assertWellFormedGateState(gateState);
129
122
 
130
123
  if (isUnlockSatisfied(gateState) || isConfigurationBypassAllowed(gateState, requireConfigured)) {
131
124
  return gateState;
132
125
  }
133
126
 
134
- throw createRewardedGateError(gateState, {
127
+ throw buildRewardedGateError(gateState, {
135
128
  errorCode,
136
129
  errorMessage
137
130
  });
@@ -0,0 +1,17 @@
1
+ // The types of the rewarded capabilities, for features that require them.
2
+
3
+ /** @typedef {ReturnType<typeof import("./service.js").createService>} RewardedCore */
4
+ /** @typedef {import("@jskit-ai/crud-core/server/types").CrudResourceApi} RewardedProviderConfigs */
5
+ /** @typedef {import("@jskit-ai/crud-core/server/types").CrudResourceApi} RewardedRules */
6
+ /** @typedef {import("@jskit-ai/crud-core/server/types").CrudResourceApi} RewardedUnlockReceipts */
7
+ /** @typedef {import("@jskit-ai/crud-core/server/types").CrudResourceApi} RewardedWatchSessions */
8
+
9
+ /**
10
+ * The `rewarded.grant-policy` capability the application provides: it decides
11
+ * whether a watch session earns its reward.
12
+ * @typedef {object} RewardedGrantPolicy
13
+ * @property {(input: { session: object, context: object, trx: import("@jskit-ai/database-runtime/server/types").RuntimeKnexTransaction }) => boolean | Promise<boolean>} authorizeGrant
14
+ * Answers true when the session's reward may be granted.
15
+ */
16
+
17
+ export {};
@@ -1,9 +1,11 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
3
 
4
- import { createActionProvider } from "@jskit-ai/kernel/server/actions";
4
+ import { ActionProvider } from "@jskit-ai/kernel/server/actions";
5
+ import { EventProvider } from "@jskit-ai/kernel/server/runtime";
6
+ import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
5
7
  import { createCapabilityRuntime, defineProvider } from "@jskit-ai/kernel/shared/capabilities";
6
- import { RewardedCoreFeature } from "../src/server/RewardedCoreProvider.js";
8
+ import { RewardedCoreFeature } from "../src/server/RewardedCoreFeature.js";
7
9
  import {
8
10
  RewardedProviderConfigsFeature,
9
11
  RewardedRulesFeature,
@@ -21,32 +23,31 @@ function valueProvider(id, capability, value) {
21
23
  });
22
24
  }
23
25
 
24
- test("Rewarded composes standard resource capabilities around one explicit domain feature", async () => {
25
- const routes = [];
26
- const resources = {};
27
- let actions;
28
- let rewarded;
26
+ function createRewardedRuntime(grantPolicy, observed = {}) {
29
27
  const knex = Object.assign(() => {}, {
30
28
  async transaction(callback) {
31
29
  return callback({});
32
30
  }
33
31
  });
34
- const runtime = createCapabilityRuntime({
32
+ return createCapabilityRuntime({
33
+ inputs: { "runtime.logger": silentLogger },
35
34
  providers: [
36
- createActionProvider(),
37
- valueProvider("test.grant-policy", "rewarded.grant-policy", { authorizeGrant: async () => false }),
35
+ EventProvider, ActionProvider,
36
+ valueProvider("test.grant-policy", "rewarded.grant-policy", grantPolicy),
38
37
  valueProvider("test.database", "runtime.database", { knex }),
39
38
  valueProvider("test.http", "runtime.http", {
40
39
  router: {
41
40
  register(method, path, contract, handler) {
42
- routes.push({ method, path, contract, handler });
41
+ observed.routes?.push({ method, path, contract, handler });
43
42
  }
44
43
  }
45
44
  }),
46
45
  valueProvider("test.json-rest-api", "runtime.json-rest-api", {
47
- resources,
46
+ resources: observed.resources ?? {},
48
47
  async addResource(name, config) {
49
- resources[name] = { config };
48
+ if (observed.resources) {
49
+ observed.resources[name] = { config };
50
+ }
50
51
  }
51
52
  }),
52
53
  RewardedRulesFeature,
@@ -60,16 +61,22 @@ test("Rewarded composes standard resource capabilities around one explicit domai
60
61
  actionCatalogue: "runtime.actions",
61
62
  rewarded: "rewarded.core"
62
63
  },
63
- setup(dependencies) {
64
- actions = dependencies.actionCatalogue;
65
- rewarded = dependencies.rewarded;
64
+ setup({ actionCatalogue, rewarded }) {
65
+ observed.actions = actionCatalogue;
66
+ observed.rewarded = rewarded;
66
67
  return {};
67
68
  }
68
69
  })
69
70
  ]
70
71
  });
72
+ }
73
+
74
+ test("Rewarded composes standard resource capabilities around one explicit domain feature", async () => {
75
+ const observed = { routes: [], resources: {} };
76
+ const runtime = createRewardedRuntime({ authorizeGrant: async () => false }, observed);
71
77
 
72
78
  await runtime.start();
79
+ const { routes, resources, actions, rewarded } = observed;
73
80
 
74
81
  const definitions = actions.listDefinitions();
75
82
  assert.equal(definitions.length, 24);
@@ -89,3 +96,9 @@ test("Rewarded composes standard resource capabilities around one explicit domai
89
96
 
90
97
  await runtime.shutdown();
91
98
  });
99
+
100
+ test("Rewarded refuses a grant policy without authorizeGrant when it starts", async () => {
101
+ const runtime = createRewardedRuntime({});
102
+
103
+ await assert.rejects(runtime.start(), /rewarded\.grant-policy requires authorizeGrant\./u);
104
+ });
@@ -0,0 +1,104 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import knexLib from "knex";
4
+ import providerConfigsMigration from "../migrations/rewarded_provider_configs_initial.cjs";
5
+ import rulesMigration from "../migrations/rewarded_rules_initial.cjs";
6
+ import unlockReceiptsMigration from "../migrations/rewarded_unlock_receipts_initial.cjs";
7
+ import watchSessionsMigration from "../migrations/rewarded_watch_sessions_initial.cjs";
8
+ import foreignKeysMigration from "../migrations/constraints/rewarded_foreign_keys.cjs";
9
+
10
+ // Knex's filename order within rewarded-core's migrations/ directory.
11
+ const TABLE_MIGRATIONS = [providerConfigsMigration, rulesMigration, unlockReceiptsMigration, watchSessionsMigration];
12
+ const TABLES = ["rewarded_provider_configs", "rewarded_rules", "rewarded_unlock_receipts", "rewarded_watch_sessions"];
13
+ const databaseUrl = process.env.REWARDED_TEST_DATABASE_URL;
14
+
15
+ function databaseOptions() {
16
+ const url = new URL(databaseUrl);
17
+ assert.equal(url.protocol, "mysql:", "Rewarded shipped migrations require MySQL.");
18
+ assert.match(url.pathname, /^\/jskit_rewarded_test_[a-z0-9_]+$/u, "Use an owned disposable rewarded test database.");
19
+ return {
20
+ client: "mysql2",
21
+ connection: {
22
+ host: url.hostname,
23
+ port: Number(url.port) || 3306,
24
+ user: decodeURIComponent(url.username),
25
+ password: decodeURIComponent(url.password),
26
+ database: url.pathname.slice(1),
27
+ ...(url.searchParams.has("socketPath") ? { socketPath: url.searchParams.get("socketPath") } : {})
28
+ },
29
+ pool: { min: 1, max: 1 }
30
+ };
31
+ }
32
+
33
+ async function foreignKeys(knex) {
34
+ return knex("information_schema.REFERENTIAL_CONSTRAINTS")
35
+ .whereRaw("CONSTRAINT_SCHEMA = DATABASE()")
36
+ .whereIn("TABLE_NAME", TABLES)
37
+ .orderBy(["TABLE_NAME", "CONSTRAINT_NAME"])
38
+ .select({ name: "CONSTRAINT_NAME", parent: "REFERENCED_TABLE_NAME", onDelete: "DELETE_RULE", onUpdate: "UPDATE_RULE" });
39
+ }
40
+
41
+ const PROVIDER_KEYS = [
42
+ { name: "fk_rewarded_unlock_receipts_provider_config", parent: "rewarded_provider_configs", onDelete: "SET NULL", onUpdate: "RESTRICT" },
43
+ { name: "fk_rewarded_watch_sessions_provider_config", parent: "rewarded_provider_configs", onDelete: "SET NULL", onUpdate: "RESTRICT" }
44
+ ];
45
+ const ALL_KEYS = [
46
+ { name: "fk_rewarded_provider_configs_workspace", parent: "workspaces", onDelete: "CASCADE", onUpdate: "RESTRICT" },
47
+ { name: "fk_rewarded_rules_workspace", parent: "workspaces", onDelete: "CASCADE", onUpdate: "RESTRICT" },
48
+ PROVIDER_KEYS[0],
49
+ { name: "fk_rewarded_unlock_receipts_user", parent: "users", onDelete: "CASCADE", onUpdate: "RESTRICT" },
50
+ { name: "fk_rewarded_unlock_receipts_watch_session", parent: "rewarded_watch_sessions", onDelete: "SET NULL", onUpdate: "RESTRICT" },
51
+ { name: "fk_rewarded_unlock_receipts_workspace", parent: "workspaces", onDelete: "CASCADE", onUpdate: "RESTRICT" },
52
+ PROVIDER_KEYS[1],
53
+ { name: "fk_rewarded_watch_sessions_user", parent: "users", onDelete: "CASCADE", onUpdate: "RESTRICT" },
54
+ { name: "fk_rewarded_watch_sessions_workspace", parent: "workspaces", onDelete: "CASCADE", onUpdate: "RESTRICT" }
55
+ ];
56
+
57
+ test("a fresh MySQL database migrates rewarded-core before users and workspaces exist, then adds its keys", {
58
+ skip: databaseUrl ? false : "REWARDED_TEST_DATABASE_URL (MySQL) is required: the shipped migrations use MySQL defaults."
59
+ }, async (t) => {
60
+ const knex = knexLib(databaseOptions());
61
+ let ownsTables = false;
62
+ t.after(async () => {
63
+ try {
64
+ if (ownsTables) {
65
+ await foreignKeysMigration.down(knex);
66
+ for (const migration of [...TABLE_MIGRATIONS].reverse()) await migration.down(knex);
67
+ await knex.schema.dropTableIfExists("users");
68
+ await knex.schema.dropTableIfExists("workspaces");
69
+ }
70
+ } finally {
71
+ await knex.destroy();
72
+ }
73
+ });
74
+ for (const table of [...TABLES, "users", "workspaces"]) {
75
+ assert.equal(await knex.schema.hasTable(table), false, `Refuse to reuse existing ${table}.`);
76
+ }
77
+ ownsTables = true;
78
+
79
+ // rewarded-core's table migrations run before users-core and workspaces-core create their tables.
80
+ for (const migration of TABLE_MIGRATIONS) await migration.up(knex);
81
+ assert.deepEqual(await foreignKeys(knex), PROVIDER_KEYS);
82
+
83
+ for (const table of ["users", "workspaces"]) {
84
+ await knex.schema.createTable(table, (builder) => builder.bigInteger("id").unsigned().primary());
85
+ }
86
+ await foreignKeysMigration.up(knex);
87
+ assert.deepEqual(await foreignKeys(knex), ALL_KEYS);
88
+
89
+ // Keys that already exist are left as they are.
90
+ await foreignKeysMigration.up(knex);
91
+ assert.deepEqual(await foreignKeys(knex), ALL_KEYS);
92
+
93
+ // A database missing a key whose rows have no parent fails clearly and keeps its rows.
94
+ await knex.schema.alterTable("rewarded_watch_sessions", (table) => table.dropForeign("user_id", "fk_rewarded_watch_sessions_user"));
95
+ await knex("workspaces").insert({ id: 1 });
96
+ await knex("rewarded_watch_sessions").insert({ workspace_id: 1, user_id: 999, gate_key: "progress" });
97
+ await assert.rejects(
98
+ foreignKeysMigration.up(knex),
99
+ /rewarded_watch_sessions\.user_id foreign key to users\.id: 1 rewarded_watch_sessions row\(s\) have a user_id with no users row/u
100
+ );
101
+ assert.equal((await knex("rewarded_watch_sessions")).length, 1);
102
+ assert.deepEqual(await foreignKeys(knex), ALL_KEYS.filter((key) => key.name !== "fk_rewarded_watch_sessions_user"));
103
+ await knex("rewarded_watch_sessions").delete();
104
+ });
@@ -53,8 +53,7 @@ test("requireRewardedUnlock allows an already unlocked gate", async () => {
53
53
  assert.deepEqual(rewardedService.calls[0], {
54
54
  input: {
55
55
  gateKey: "progress-logging",
56
- workspaceSlug: "alpha",
57
- surface: "app"
56
+ workspaceSlug: "alpha"
58
57
  },
59
58
  options: {
60
59
  context: REQUEST_CONTEXT
@@ -235,12 +234,9 @@ test("requireRewardedUnlock fails closed when the rewarded service returns an in
235
234
  }
236
235
  ),
237
236
  (error) => {
238
- assert.equal(error.statusCode, 503);
239
- assert.equal(error.code, "rewarded_gate_state_invalid");
240
- assert.deepEqual(error.details.rewardedGate, {
241
- gateKey: "progress-logging",
242
- workspaceSlug: "alpha"
243
- });
237
+ assert.equal(error.message, "Rewarded gate returned an invalid state.");
238
+ assert.equal(error.statusCode, undefined);
239
+ assert.equal(error.code, undefined);
244
240
  return true;
245
241
  }
246
242
  );
@@ -266,8 +262,9 @@ test("requireRewardedUnlock fails closed when a non-blocking gate state has no e
266
262
  }
267
263
  ),
268
264
  (error) => {
269
- assert.equal(error.statusCode, 503);
270
- assert.equal(error.code, "rewarded_gate_state_invalid");
265
+ assert.equal(error.message, "Rewarded gate returned an invalid state.");
266
+ assert.equal(error.statusCode, undefined);
267
+ assert.equal(error.code, undefined);
271
268
  return true;
272
269
  }
273
270
  );
@@ -1,7 +1,7 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
3
 
4
- import { registerRoutes } from "../src/server/registerRoutes.js";
4
+ import { registerRewardedRoutes } from "../src/server/rewardedRoutes.js";
5
5
 
6
6
  function createReplyDouble() {
7
7
  return {
@@ -35,7 +35,7 @@ function mountRoutes() {
35
35
  }
36
36
  };
37
37
 
38
- registerRoutes(router);
38
+ registerRewardedRoutes(router);
39
39
  return registeredRoutes;
40
40
  }
41
41
 
@@ -1,6 +1,7 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
3
  import knexLib from "knex";
4
+ import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
4
5
  import { toDatabaseDateTimeUtc } from "@jskit-ai/database-runtime/shared";
5
6
  import { createCrudJsonApiRepository } from "@jskit-ai/crud-core/server/jsonApiRepository";
6
7
  import {
@@ -91,7 +92,7 @@ test(`rewarded grants use real resources and atomic transactions (${databaseUrl
91
92
  await knex("users").insert([{ id: 7 }, { id: 8 }]);
92
93
  await knex("workspaces").insert([{ id: 1 }, { id: 2 }]);
93
94
 
94
- const api = await createJsonRestApiHost({ knex });
95
+ const api = await createJsonRestApiHost({ knex, logger: silentLogger });
95
96
  const repositories = {};
96
97
  for (const [scopeName, resource, migration] of RESOURCES) {
97
98
  await addResourceIfMissing(api, scopeName, createJsonRestResourceScopeOptions(resource, {
@@ -142,13 +143,15 @@ test(`rewarded grants use real resources and atomic transactions (${databaseUrl
142
143
  rewardedRulesRepository: repositories.rewardedRules,
143
144
  rewardedWatchSessionsRepository: repositories.rewardedWatchSessions,
144
145
  rewardedUnlockReceiptsRepository: repositories.rewardedUnlockReceipts,
145
- async authorizeGrant({ session, context: grantContext, trx }) {
146
- transactions.set(grantContext.testCase, trx);
147
- const stored = await trx("rewarded_watch_sessions").where({ id: session.id }).first();
148
- assert.equal(String(stored.user_id), grantContext.scopeValues.userId);
149
- assert.equal(String(stored.workspace_id), grantContext.scopeValues.workspaceId);
150
- assert.equal(events.some((entry) => entry.event === "afterCommit" && entry.testCase === grantContext.testCase), false);
151
- return authorize;
146
+ grantPolicy: {
147
+ async authorizeGrant({ session, context: grantContext, trx }) {
148
+ transactions.set(grantContext.testCase, trx);
149
+ const stored = await trx("rewarded_watch_sessions").where({ id: session.id }).first();
150
+ assert.equal(String(stored.user_id), grantContext.scopeValues.userId);
151
+ assert.equal(String(stored.workspace_id), grantContext.scopeValues.workspaceId);
152
+ assert.equal(events.some((entry) => entry.event === "afterCommit" && entry.testCase === grantContext.testCase), false);
153
+ return authorize;
154
+ }
152
155
  }
153
156
  });
154
157
  const gate = { workspaceSlug: "alpha", gateKey: "progress" };
@@ -101,7 +101,7 @@ const REQUEST_CONTEXT = Object.freeze({
101
101
 
102
102
  test("getCurrentState reports a blocked gate when rule and provider config exist without an active unlock", async () => {
103
103
  const service = createService({
104
- authorizeGrant: async () => true,
104
+ grantPolicy: { authorizeGrant: async () => true },
105
105
  rewardedRulesRepository: createRuleRepository([
106
106
  {
107
107
  id: "11",
@@ -148,7 +148,7 @@ test("getCurrentState reports a blocked gate when rule and provider config exist
148
148
  test("getCurrentState reuses an active unlock receipt instead of blocking", async () => {
149
149
  const futureDate = new Date(Date.now() + 15 * 60 * 1000).toISOString();
150
150
  const service = createService({
151
- authorizeGrant: async () => true,
151
+ grantPolicy: { authorizeGrant: async () => true },
152
152
  rewardedRulesRepository: createRuleRepository([
153
153
  {
154
154
  id: "11",
@@ -203,7 +203,7 @@ test("getCurrentState ignores caller surface overrides and evaluates the app-sur
203
203
  const recordedRuleQueries = [];
204
204
  const recordedConfigQueries = [];
205
205
  const service = createService({
206
- authorizeGrant: async () => true,
206
+ grantPolicy: { authorizeGrant: async () => true },
207
207
  rewardedRulesRepository: {
208
208
  async queryDocuments(query) {
209
209
  recordedRuleQueries.push(query);
@@ -279,7 +279,7 @@ test("grantReward patches the watch session and creates an unlock receipt", asyn
279
279
  };
280
280
 
281
281
  const service = createService({
282
- authorizeGrant: async () => true,
282
+ grantPolicy: { authorizeGrant: async () => true },
283
283
  rewardedRulesRepository: createRuleRepository([
284
284
  {
285
285
  id: "11",
@@ -339,16 +339,15 @@ test("grant policy sees stored session and server context and rejects before wri
339
339
  async createDocument() { throw new Error("Must not write a receipt"); }
340
340
  }
341
341
  };
342
- assert.throws(() => createService(dependencies), /authorizeGrant policy/);
343
342
  for (const decision of [false, undefined, "true"]) {
344
- const service = createService({ ...dependencies, authorizeGrant: async ({ session, context, trx }) => {
343
+ const service = createService({ ...dependencies, grantPolicy: { authorizeGrant: async ({ session, context, trx }) => {
345
344
  calls += 1;
346
345
  assert.equal(session.id, "41");
347
346
  assert.equal(session.gateKey, "bonus");
348
347
  assert.equal(context, REQUEST_CONTEXT);
349
348
  assert.ok(trx);
350
349
  return decision;
351
- } });
350
+ } } });
352
351
  await assert.rejects(service.grantReward({ workspaceSlug: "alpha", sessionId: "41",
353
352
  authorized: true, gateKey: "forged" }, { context: REQUEST_CONTEXT }), /Reward grant is not authorized/);
354
353
  }
@@ -1,136 +0,0 @@
1
- import {
2
- currentQueryInputValidator,
3
- startCommandInputValidator,
4
- grantCommandInputValidator,
5
- closeCommandInputValidator,
6
- currentStateOutputValidator,
7
- startGateOutputValidator,
8
- grantRewardOutputValidator,
9
- closeSessionOutputValidator
10
- } from "./inputSchemas.js";
11
- import { createEntityChangedActionEvent } from "@jskit-ai/kernel/server/actions";
12
- import { resolveCrudRecordChangedEvent } from "@jskit-ai/resource-crud-core/shared/crudNamespaceSupport";
13
-
14
- const ACTION_CURRENT = "rewarded.current.read";
15
- const ACTION_START = "rewarded.start";
16
- const ACTION_GRANT = "rewarded.grant";
17
- const ACTION_CLOSE = "rewarded.close";
18
-
19
- const watchSessionChanged = resolveCrudRecordChangedEvent("rewarded_watch_sessions");
20
- const unlockReceiptChanged = resolveCrudRecordChangedEvent("rewarded_unlock_receipts");
21
-
22
- function changedEvent({ entity, operation, entityId, event }) {
23
- return createEntityChangedActionEvent({
24
- source: "rewarded",
25
- entity,
26
- operation,
27
- entityId,
28
- realtime: { event, audience: "event_scope" }
29
- });
30
- }
31
-
32
- function createRewardedActions({ rewarded } = {}) {
33
- if (!rewarded) {
34
- throw new TypeError("createRewardedActions requires rewarded.");
35
- }
36
- return Object.freeze([
37
- {
38
- id: ACTION_CURRENT,
39
- version: 1,
40
- kind: "query",
41
- channels: ["api", "automation", "internal"],
42
- surfaces: ["app"],
43
- permission: { require: "authenticated" },
44
- input: currentQueryInputValidator,
45
- output: currentStateOutputValidator,
46
- idempotency: "none",
47
- async execute(input, context) {
48
- return rewarded.getCurrentState(input, {
49
- context
50
- });
51
- }
52
- },
53
- {
54
- id: ACTION_START,
55
- version: 1,
56
- kind: "command",
57
- channels: ["api", "automation", "internal"],
58
- surfaces: ["app"],
59
- permission: { require: "authenticated" },
60
- input: startCommandInputValidator,
61
- output: startGateOutputValidator,
62
- idempotency: "optional",
63
- events: [changedEvent({
64
- entity: "watch-session",
65
- operation: "created",
66
- entityId: ({ result }) => result?.session?.id,
67
- event: watchSessionChanged
68
- })],
69
- async execute(input, context) {
70
- return rewarded.startGate(input, {
71
- context
72
- });
73
- }
74
- },
75
- {
76
- id: ACTION_GRANT,
77
- version: 1,
78
- kind: "command",
79
- channels: ["api", "automation", "internal"],
80
- surfaces: ["app"],
81
- permission: { require: "authenticated" },
82
- input: grantCommandInputValidator,
83
- output: grantRewardOutputValidator,
84
- idempotency: "optional",
85
- events: [
86
- changedEvent({
87
- entity: "watch-session",
88
- operation: "updated",
89
- entityId: ({ result }) => result?.session?.id,
90
- event: watchSessionChanged
91
- }),
92
- changedEvent({
93
- entity: "unlock-receipt",
94
- operation: "created",
95
- entityId: ({ result }) => result?.unlock?.id,
96
- event: unlockReceiptChanged
97
- })
98
- ],
99
- async execute(input, context) {
100
- return rewarded.grantReward(input, {
101
- context
102
- });
103
- }
104
- },
105
- {
106
- id: ACTION_CLOSE,
107
- version: 1,
108
- kind: "command",
109
- channels: ["api", "automation", "internal"],
110
- surfaces: ["app"],
111
- permission: { require: "authenticated" },
112
- input: closeCommandInputValidator,
113
- output: closeSessionOutputValidator,
114
- idempotency: "optional",
115
- events: [changedEvent({
116
- entity: "watch-session",
117
- operation: "updated",
118
- entityId: ({ result }) => result?.session?.id,
119
- event: watchSessionChanged
120
- })],
121
- async execute(input, context) {
122
- return rewarded.closeSession(input, {
123
- context
124
- });
125
- }
126
- }
127
- ]);
128
- }
129
-
130
- export {
131
- ACTION_CURRENT,
132
- ACTION_START,
133
- ACTION_GRANT,
134
- ACTION_CLOSE,
135
- createRewardedActions
136
- };