@owlmeans/server-job 0.1.18-rc.9 → 0.1.18

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 (97) hide show
  1. package/README.md +46 -5
  2. package/agent-meta/manifest.json +3 -3
  3. package/agent-meta/skills/server-job/SKILL.md +60 -108
  4. package/build/actions/cancel.d.ts +4 -3
  5. package/build/actions/cancel.d.ts.map +1 -1
  6. package/build/actions/cancel.js +15 -7
  7. package/build/actions/cancel.js.map +1 -1
  8. package/build/actions/get.d.ts +4 -3
  9. package/build/actions/get.d.ts.map +1 -1
  10. package/build/actions/get.js +10 -5
  11. package/build/actions/get.js.map +1 -1
  12. package/build/actions/list.d.ts +4 -3
  13. package/build/actions/list.d.ts.map +1 -1
  14. package/build/actions/list.js +16 -15
  15. package/build/actions/list.js.map +1 -1
  16. package/build/actions/watch.d.ts +5 -4
  17. package/build/actions/watch.d.ts.map +1 -1
  18. package/build/actions/watch.js +44 -38
  19. package/build/actions/watch.js.map +1 -1
  20. package/build/helper.d.ts +1 -1
  21. package/build/helper.d.ts.map +1 -1
  22. package/build/helper.js.map +1 -1
  23. package/build/index.d.ts +0 -3
  24. package/build/index.d.ts.map +1 -1
  25. package/build/index.js +0 -3
  26. package/build/index.js.map +1 -1
  27. package/build/types.d.ts +19 -66
  28. package/build/types.d.ts.map +1 -1
  29. package/build/utils/consts.local.d.ts +5 -0
  30. package/build/utils/consts.local.d.ts.map +1 -0
  31. package/build/utils/consts.local.js +5 -0
  32. package/build/utils/consts.local.js.map +1 -0
  33. package/build/utils/index.d.ts +5 -2
  34. package/build/utils/index.d.ts.map +1 -1
  35. package/build/utils/index.js +2 -2
  36. package/build/utils/index.js.map +1 -1
  37. package/build/utils/policy/types.d.ts +11 -0
  38. package/build/utils/policy/types.d.ts.map +1 -0
  39. package/build/utils/policy/types.js +2 -0
  40. package/build/utils/policy/types.js.map +1 -0
  41. package/build/utils/policy.d.ts +4 -0
  42. package/build/utils/policy.d.ts.map +1 -0
  43. package/build/utils/policy.js +12 -0
  44. package/build/utils/policy.js.map +1 -0
  45. package/build/utils/types.d.ts +11 -0
  46. package/build/utils/types.d.ts.map +1 -0
  47. package/build/utils/types.js +2 -0
  48. package/build/utils/types.js.map +1 -0
  49. package/build/utils/view/types.d.ts +13 -0
  50. package/build/utils/view/types.d.ts.map +1 -0
  51. package/build/utils/view/types.js +2 -0
  52. package/build/utils/view/types.js.map +1 -0
  53. package/build/utils/view.d.ts +4 -0
  54. package/build/utils/view.d.ts.map +1 -0
  55. package/build/utils/view.js +92 -0
  56. package/build/utils/view.js.map +1 -0
  57. package/package.json +20 -16
  58. package/src/actions/cancel.ts +17 -8
  59. package/src/actions/get.ts +12 -6
  60. package/src/actions/list.ts +21 -20
  61. package/src/actions/watch.ts +47 -38
  62. package/src/helper.ts +1 -1
  63. package/src/index.ts +0 -3
  64. package/src/types.ts +23 -59
  65. package/src/utils/consts.local.ts +7 -0
  66. package/src/utils/index.ts +5 -2
  67. package/src/utils/policy/types.ts +11 -0
  68. package/src/utils/policy.ts +20 -0
  69. package/src/utils/types.ts +11 -0
  70. package/src/utils/view/types.ts +13 -0
  71. package/src/utils/view.ts +91 -0
  72. package/tests/view.spec.ts +55 -0
  73. package/build/consts.d.ts +0 -26
  74. package/build/consts.d.ts.map +0 -1
  75. package/build/consts.js +0 -26
  76. package/build/consts.js.map +0 -1
  77. package/build/entrypoints.d.ts +0 -20
  78. package/build/entrypoints.d.ts.map +0 -1
  79. package/build/entrypoints.js +0 -46
  80. package/build/entrypoints.js.map +0 -1
  81. package/build/schemas.d.ts +0 -10
  82. package/build/schemas.d.ts.map +0 -1
  83. package/build/schemas.js +0 -17
  84. package/build/schemas.js.map +0 -1
  85. package/build/utils/owner.d.ts +0 -33
  86. package/build/utils/owner.d.ts.map +0 -1
  87. package/build/utils/owner.js +0 -41
  88. package/build/utils/owner.js.map +0 -1
  89. package/build/utils/resource.d.ts +0 -23
  90. package/build/utils/resource.d.ts.map +0 -1
  91. package/build/utils/resource.js +0 -28
  92. package/build/utils/resource.js.map +0 -1
  93. package/src/consts.ts +0 -28
  94. package/src/entrypoints.ts +0 -61
  95. package/src/schemas.ts +0 -19
  96. package/src/utils/owner.ts +0 -60
  97. package/src/utils/resource.ts +0 -40
@@ -1,10 +1,10 @@
1
+ import type { EntrypointProtocolDeclaration } from '@owlmeans/entrypoint'
1
2
  import { handlers } from '@owlmeans/server-api'
2
- import type { Criteria } from '@owlmeans/resource'
3
- import type { JobRecord } from '@owlmeans/queue'
4
- import type { JobState } from '@owlmeans/queue'
5
- import { DEFAULT_JOB_SORT } from '../consts.js'
3
+ import type { BoundEntrypointHandler } from '@owlmeans/server-entrypoint'
4
+ import type { JobView } from '@owlmeans/job'
5
+ import type { ListResult } from '@owlmeans/resource'
6
6
  import type { Context, JobEntrypoints, JobHandlerOptions, JobListQuery } from '../types.js'
7
- import { jobScope, jobViewer, jobsOf } from '../utils/index.js'
7
+ import { makeJobPolicyHelper } from '../utils/index.js'
8
8
 
9
9
  /**
10
10
  * The caller's jobs, newest first.
@@ -16,20 +16,21 @@ import { jobScope, jobViewer, jobsOf } from '../utils/index.js'
16
16
  */
17
17
  export const listJobs = (
18
18
  protocol: JobEntrypoints['list'],
19
- opts?: JobHandlerOptions
20
- ): ReturnType<ReturnType<typeof handlers<Context>>['request']> => handlers<Context>().request(protocol, async (req, ctx) => {
21
- const resource = jobsOf(ctx, opts)
22
- const viewer = await jobViewer(req, ctx, opts)
23
- const query = (req.query ?? {}) as JobListQuery
19
+ opts: JobHandlerOptions
20
+ ): BoundEntrypointHandler<EntrypointProtocolDeclaration> => {
21
+ const policy = makeJobPolicyHelper(opts)
24
22
 
25
- const where: Criteria<JobRecord> = {
26
- ...jobScope(viewer, opts),
27
- ...(query.state != null ? { state: query.state as JobState } : {}),
28
- ...(query.name != null ? { name: query.name } : {}),
29
- }
30
-
31
- return await resource.list(where, {
32
- sort: [{ field: DEFAULT_JOB_SORT, order: 'desc' }],
33
- ...(query.size != null ? { size: query.size, page: query.page ?? 0 } : {}),
23
+ return handlers<Context>().request(protocol, async (req, ctx) => {
24
+ const resource = policy.jobsOf(ctx)
25
+ const audience = await opts.policy.audience(req, ctx)
26
+ const query = (req.query ?? {}) as JobListQuery
27
+ const listed = await resource.list(opts.policy.where(audience, query), {
28
+ sort: [{ field: 'createdAt', order: 'desc' }],
29
+ ...(query.size != null ? { size: query.size, page: query.page ?? 0 } : {}),
30
+ })
31
+ return {
32
+ ...listed,
33
+ items: await Promise.all(listed.items.map(record => opts.policy.map(record, audience))),
34
+ } satisfies ListResult<JobView>
34
35
  })
35
- })
36
+ }
@@ -1,16 +1,22 @@
1
+ import type { EntrypointProtocolDeclaration } from '@owlmeans/entrypoint'
2
+ import type { BoundEntrypointHandler } from '@owlmeans/server-entrypoint'
1
3
  import { connection } from '@owlmeans/server-socket'
2
4
  import type { EventMessage } from '@owlmeans/socket'
3
5
  import { MessageType } from '@owlmeans/socket'
6
+ import { JOB_EVENT } from '@owlmeans/job'
7
+ import type { JobViewEvent } from '@owlmeans/job'
4
8
  import type { JobEvent } from '@owlmeans/queue'
5
- import { JOB_EVENT } from '../consts.js'
9
+ import { logger } from '@owlmeans/log'
6
10
  import type { Context, JobEntrypoints, JobHandlerOptions } from '../types.js'
7
- import { jobViewer, jobsOf, owns } from '../utils/index.js'
11
+ import { makeJobPolicyHelper } from '../utils/index.js'
12
+
13
+ const log = logger('server-job:watch')
8
14
 
9
15
  /**
10
16
  * Push this caller's job lifecycle events down a socket.
11
17
  *
12
- * The frames are `JobEvent`s exactly as the queue publishes them, under the {@link JOB_EVENT}
13
- * event name — no shape of this package's own, so a client applies them with the contract types.
18
+ * Broker events are resolved inside the caller's audience and mapped to {@link JobViewEvent}; raw
19
+ * queue ids, payloads, failures and ownership fields never cross the socket boundary.
14
20
  *
15
21
  * **A `JobEvent` carries no owner**, so each one is attributed by reading its job back, and the
16
22
  * ids that answered are remembered for the life of the connection. A queue configured with
@@ -20,46 +26,49 @@ import { jobViewer, jobsOf, owns } from '../utils/index.js'
20
26
  */
21
27
  export const watchJobs = (
22
28
  protocol: JobEntrypoints['watch'],
23
- opts?: JobHandlerOptions
24
- ): ReturnType<typeof connection> => connection<typeof protocol, Context>(protocol, async (conn, ctx, req) => {
25
- const resource = jobsOf(ctx, opts)
26
- const viewer = await jobViewer(req, ctx, opts)
27
- const mine = new Set<string>()
29
+ opts: JobHandlerOptions
30
+ ): BoundEntrypointHandler<EntrypointProtocolDeclaration> => {
31
+ const policy = makeJobPolicyHelper(opts)
28
32
 
29
- const attributable = async (event: JobEvent): Promise<boolean> => {
30
- if (viewer == null || mine.has(event.id)) {
31
- return true
32
- }
33
- const record = await resource.load(event.id)
34
- if (record == null || !owns(record, viewer, opts)) {
35
- return false
36
- }
37
- mine.add(event.id)
33
+ return connection<typeof protocol, Context>(protocol, async (conn, ctx, req) => {
34
+ const resource = policy.jobsOf(ctx)
35
+ const audience = await opts.policy.audience(req, ctx)
36
+ const publicIds = new Map<string, string>()
38
37
 
39
- return true
40
- }
41
-
42
- const unsubscribe = await resource.subscribe(async event => {
43
- try {
44
- if (await attributable(event)) {
45
- await conn.notify(JOB_EVENT, event)
38
+ const project = async (event: JobEvent): Promise<JobViewEvent | null> => {
39
+ const record = await resource.load({
40
+ $and: [{ id: event.id }, opts.policy.where(audience, {})],
41
+ })
42
+ if (record != null) {
43
+ const job = await opts.policy.map(record, audience)
44
+ publicIds.set(event.id, job.id)
45
+ return { type: 'upsert', job }
46
46
  }
47
- } catch (e) {
48
- console.error('Job watch notify error:', e)
47
+ const id = publicIds.get(event.id)
48
+ return id == null ? null : { type: 'remove', id }
49
49
  }
50
- })
51
50
 
52
- conn.listen(async message => {
53
- if (typeof message !== 'object') {
54
- return
55
- }
56
- const msg = message as EventMessage<void>
57
- if (msg.type === MessageType.System && msg.event === 'close') {
51
+ const unsubscribe = await resource.subscribe(async event => {
58
52
  try {
59
- await unsubscribe()
53
+ const projected = await project(event)
54
+ if (projected != null) await conn.notify(JOB_EVENT, projected)
60
55
  } catch (e) {
61
- console.error('Job watch unsubscribe error:', e)
56
+ log.warn('Job watch notify failed', { id: event.id, queue: event.queue, error: e })
62
57
  }
63
- }
58
+ })
59
+
60
+ conn.listen(async message => {
61
+ if (typeof message !== 'object') {
62
+ return
63
+ }
64
+ const msg = message as EventMessage<void>
65
+ if (msg.type === MessageType.System && msg.event === 'close') {
66
+ try {
67
+ await unsubscribe()
68
+ } catch (e) {
69
+ log.warn('Job watch unsubscribe failed', e)
70
+ }
71
+ }
72
+ })
64
73
  })
65
- })
74
+ }
package/src/helper.ts CHANGED
@@ -11,7 +11,7 @@ import type { JobEntrypoints, JobHandlerOptions } from './types.js'
11
11
  *
12
12
  * @throws {SyntaxError} when the array carries no group under that root.
13
13
  */
14
- export const serveJobEntrypoints = (entrypoints: JobEntrypoints, opts?: JobHandlerOptions) => [
14
+ export const serveJobEntrypoints = (entrypoints: JobEntrypoints, opts: JobHandlerOptions) => [
15
15
  bind(entrypoints.base),
16
16
  bind(entrypoints.list, listJobs(entrypoints.list, opts)),
17
17
  bind(entrypoints.watch, watchJobs(entrypoints.watch, opts)),
package/src/index.ts CHANGED
@@ -1,8 +1,5 @@
1
1
  export type * from './types.js'
2
2
 
3
- export * from './consts.js'
4
- export * from './schemas.js'
5
- export * from './entrypoints.js'
6
3
  export * from './helper.js'
7
4
  export * from './actions/index.js'
8
5
  export * from './utils/index.js'
package/src/types.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  import type { BasicConfig, BasicContext } from '@owlmeans/context'
2
2
  import type { AbstractRequest } from '@owlmeans/entrypoint'
3
- import type { QueueAppend, QueueConfig } from '@owlmeans/queue'
3
+ import type { JobEntrypoints, JobListQuery, JobView } from '@owlmeans/job'
4
+ import type { JobRecord, QueueAppend, QueueConfig, QueueResource } from '@owlmeans/queue'
5
+ import type { Criteria } from '@owlmeans/resource'
4
6
  import type { ApiServerAppend } from '@owlmeans/server-api'
5
7
  import type { ServerConfig, ServerContext } from '@owlmeans/server-context'
6
- import type { EntrypointProtocol, OpenRequest, OpenValue } from '@owlmeans/entrypoint'
7
8
 
8
9
  export interface Config extends ServerConfig {
9
10
  queue?: QueueConfig
@@ -12,65 +13,28 @@ export interface Config extends ServerConfig {
12
13
  export interface Context<C extends Config = Config> extends ServerContext<C>,
13
14
  ApiServerAppend, QueueAppend { }
14
15
 
15
- /** The alias every entrypoint of one job group answers under, derived from the group's root. */
16
- export interface JobEntrypointAliases {
17
- base: string
18
- list: string
19
- get: string
20
- cancel: string
21
- watch: string
16
+ // Kept as a type: a `Record` (mapped type) that an application's audience satisfies without declaring an index signature.
17
+ export type JobAudience = Record<string, unknown>
18
+
19
+ /** Required application policy at the raw-broker to public-domain boundary. */
20
+ export interface JobExposurePolicy<A extends JobAudience = JobAudience> {
21
+ audience: (req: AbstractRequest, ctx: BasicContext<BasicConfig>) => A | Promise<A>
22
+ /** Translate public filters and authenticated scope into broker criteria. */
23
+ where: (audience: A, query: JobListQuery) => Criteria<JobRecord>
24
+ /** Resolve an opaque public id within the authenticated scope. */
25
+ lookup: (
26
+ id: string, audience: A, resource: QueueResource
27
+ ) => Promise<JobRecord | null>
28
+ /** Allowlist and map a scoped broker record into its public representation. */
29
+ map: (record: JobRecord, audience: A) => JobView | Promise<JobView>
30
+ /** Cancellation is unavailable unless this callback is present and approves the record. */
31
+ cancel?: (record: JobRecord, audience: A) => boolean | Promise<boolean>
22
32
  }
23
33
 
24
- /** The immutable declarations for one job group, addressed by property rather than alias lookup. */
25
- export interface JobEntrypoints {
26
- base: EntrypointProtocol<OpenRequest, OpenValue>
27
- list: EntrypointProtocol<{ query: JobListQuery }, unknown>
28
- get: EntrypointProtocol<{ params: { id: string } }, unknown>
29
- cancel: EntrypointProtocol<{ params: { id: string } }, unknown>
30
- watch: EntrypointProtocol<OpenRequest, void>
31
- }
32
-
33
- export interface JobEntrypointOptions {
34
- /** The path segment the group answers under. Defaults to `/jobs`. */
35
- path?: string
36
- /** The entrypoint the group hangs under — an app's API base. Top level when omitted. */
37
- parent?: string
38
- /** The service route the group answers on, when it is not this app's own. */
39
- service?: string
40
- /**
41
- * The guard the group's base carries, and every entrypoint under it inherits.
42
- *
43
- * `DEFAULT_GUARD` unless told otherwise, because ownership is derived from the authenticated
44
- * subject and an unguarded declaration has no subject to derive it from. Pass `null` only for a
45
- * group that is scoped some other way — its handlers then answer `AuthorizationError`.
46
- */
47
- guard?: string | null
48
- }
49
-
50
- /** The list entrypoint's query, as it travels on the wire. */
51
- export interface JobListQuery {
52
- state?: string
53
- name?: string
54
- page?: number
55
- size?: number
56
- }
57
-
58
- /**
59
- * A request that may read the queue unscoped.
60
- *
61
- * A predicate rather than a permission name: which permission, gate or role means "operator" is
62
- * the application's decision, and hardcoding one here would make every deployment that names it
63
- * differently patch this package.
64
- */
65
- export interface JobAdminCheck {
66
- (req: AbstractRequest, ctx: BasicContext<BasicConfig>): boolean | Promise<boolean>
67
- }
68
-
69
- export interface JobHandlerOptions {
34
+ export interface JobHandlerOptions<A extends JobAudience = JobAudience> {
70
35
  /** Which declared queue these handlers read. The context's sole queue when omitted. */
71
36
  queue?: string
72
- /** The field inside `JobRecord.data` that names the owner. Defaults to `owner`. */
73
- ownerField?: string
74
- /** The escape hatch — see {@link JobAdminCheck}. Nothing is unscoped without one. */
75
- admin?: JobAdminCheck
37
+ policy: JobExposurePolicy<A>
76
38
  }
39
+
40
+ export type { JobEntrypoints, JobListQuery }
@@ -0,0 +1,7 @@
1
+ export const MAX_JSON_DEPTH = 8
2
+
3
+ export const MAX_JSON_ITEMS = 100
4
+
5
+ export const MAX_JSON_STRING = 16_384
6
+
7
+ export const FORBIDDEN_KEYS = new Set(['__proto__', 'prototype', 'constructor'])
@@ -1,2 +1,5 @@
1
- export * from './owner.js'
2
- export * from './resource.js'
1
+ export * from './policy.js'
2
+ export * from './view.js'
3
+ export type * from './types.js'
4
+ export type * from './policy/types.js'
5
+ export type * from './view/types.js'
@@ -0,0 +1,11 @@
1
+ import type { BasicConfig, BasicContext } from '@owlmeans/context'
2
+ import type { JobRecord, QueueResource } from '@owlmeans/queue'
3
+ import type { JobAudience } from '../../types.js'
4
+
5
+ /** The queue and the records one set of job handlers may reach, under its exposure policy. */
6
+ export interface JobPolicyHelper<A extends JobAudience = JobAudience> {
7
+ /** The queue these handlers read: the one the options name, else the context's sole queue. */
8
+ jobsOf: <D = unknown, R = unknown>(ctx: BasicContext<BasicConfig>) => QueueResource<D, R>
9
+ /** Resolve an opaque id without revealing whether it exists outside the current audience. */
10
+ readExposedJob: (resource: QueueResource, id: string, audience: A) => Promise<JobRecord>
11
+ }
@@ -0,0 +1,20 @@
1
+ import type { BasicConfig, BasicContext } from '@owlmeans/context'
2
+ import type { JobRecord, QueueResource } from '@owlmeans/queue'
3
+ import { UnknownJob } from '@owlmeans/queue'
4
+ import type { Context, JobAudience, JobHandlerOptions } from '../types.js'
5
+ import type { JobPolicyHelper } from './policy/types.js'
6
+
7
+ export const makeJobPolicyHelper = <A extends JobAudience = JobAudience>(
8
+ opts: JobHandlerOptions<A>
9
+ ): JobPolicyHelper<A> => {
10
+ const jobsOf = <D = unknown, R = unknown>(ctx: BasicContext<BasicConfig>): QueueResource<D, R> =>
11
+ (ctx as unknown as Context).jobs<D, R>(opts.queue)
12
+
13
+ const readExposedJob = async (resource: QueueResource, id: string, audience: A): Promise<JobRecord> => {
14
+ const record = await opts.policy.lookup(id, audience, resource)
15
+ if (record == null) throw new UnknownJob('job')
16
+ return record
17
+ }
18
+
19
+ return { jobsOf, readExposedJob }
20
+ }
@@ -0,0 +1,11 @@
1
+ import type { JobJson, PublicJobError } from '@owlmeans/job'
2
+
3
+ export interface JobViewFields {
4
+ id: string
5
+ kind: string
6
+ summary?: string
7
+ metadata?: Record<string, JobJson>
8
+ result?: JobJson
9
+ error?: PublicJobError
10
+ cancellable?: boolean
11
+ }
@@ -0,0 +1,13 @@
1
+ import type { JobJson, JobView, PublicJobError } from '@owlmeans/job'
2
+ import type { JobRecord } from '@owlmeans/queue'
3
+ import type { JobViewFields } from '../types.js'
4
+
5
+ /** The public projection of a broker job: nothing crosses the boundary that was not allowlisted. */
6
+ export interface JobViewHelper {
7
+ /** Copy JSON through bounded, prototype-free containers and discard every non-JSON value. */
8
+ sanitizeJobJson: (value: unknown, depth?: number) => JobJson | undefined
9
+ /** Build a public view from fields an application explicitly allowlisted. */
10
+ jobViewOf: (record: JobRecord, fields: JobViewFields) => JobView
11
+ /** Safe default for a broker failure; raw reasons and stacks never cross the boundary. */
12
+ publicJobError: (type?: string) => PublicJobError
13
+ }
@@ -0,0 +1,91 @@
1
+ import { JobViewStatus, type JobJson, type JobProgressView, type JobView, type PublicJobError } from '@owlmeans/job'
2
+ import { JobState, type JobRecord } from '@owlmeans/queue'
3
+ import { FORBIDDEN_KEYS, MAX_JSON_DEPTH, MAX_JSON_ITEMS, MAX_JSON_STRING } from './consts.local.js'
4
+ import type { JobViewFields } from './types.js'
5
+ import type { JobViewHelper } from './view/types.js'
6
+
7
+ export const createJobViewHelper = (): JobViewHelper => {
8
+ const sanitizeJobJson = (value: unknown, depth: number = 0): JobJson | undefined => {
9
+ if (depth > MAX_JSON_DEPTH) return undefined
10
+ if (value == null || typeof value === 'boolean' || typeof value === 'string') {
11
+ return typeof value === 'string' ? value.slice(0, MAX_JSON_STRING) : value
12
+ }
13
+ if (typeof value === 'number') return Number.isFinite(value) ? value : undefined
14
+ if (Array.isArray(value)) {
15
+ return value.slice(0, MAX_JSON_ITEMS)
16
+ .map(item => sanitizeJobJson(item, depth + 1))
17
+ .filter((item): item is JobJson => item !== undefined)
18
+ }
19
+ if (typeof value !== 'object') return undefined
20
+
21
+ const result: Record<string, JobJson> = Object.create(null) as Record<string, JobJson>
22
+ for (const [key, item] of Object.entries(value).slice(0, MAX_JSON_ITEMS)) {
23
+ if (FORBIDDEN_KEYS.has(key)) continue
24
+ const safe = sanitizeJobJson(item, depth + 1)
25
+ if (safe !== undefined) result[key] = safe
26
+ }
27
+ return result
28
+ }
29
+
30
+ const sanitizeError = (error: PublicJobError | undefined): PublicJobError | undefined => error == null
31
+ ? undefined
32
+ : {
33
+ type: error.type.slice(0, 128),
34
+ message: error.message.slice(0, 2048),
35
+ }
36
+
37
+ const statusOf = (state?: JobState): JobViewStatus => {
38
+ switch (state) {
39
+ case JobState.Active: return JobViewStatus.Running
40
+ case JobState.Completed: return JobViewStatus.Succeeded
41
+ case JobState.Failed: return JobViewStatus.Failed
42
+ default: return JobViewStatus.Queued
43
+ }
44
+ }
45
+
46
+ const progressOf = (value: unknown): JobProgressView | undefined => {
47
+ if (typeof value === 'number' && Number.isFinite(value)) return { percent: value }
48
+ if (value == null || typeof value !== 'object' || Array.isArray(value)) return undefined
49
+ const raw = value as Record<string, unknown>
50
+ const progress: JobProgressView = {}
51
+ if (typeof raw.percent === 'number' && Number.isFinite(raw.percent)) progress.percent = raw.percent
52
+ if (typeof raw.done === 'number' && Number.isFinite(raw.done)) progress.done = raw.done
53
+ if (typeof raw.total === 'number' && Number.isFinite(raw.total)) progress.total = raw.total
54
+ if (typeof raw.message === 'string') progress.message = raw.message.slice(0, 512)
55
+ return Object.keys(progress).length === 0 ? undefined : progress
56
+ }
57
+
58
+ const jobViewOf = (record: JobRecord, fields: JobViewFields): JobView => {
59
+ const createdAt = record.createdAt ?? new Date(0).toISOString()
60
+ const updatedAt = record.finishedAt ?? record.startedAt ?? createdAt
61
+ const progress = progressOf(record.progress)
62
+ const metadata = sanitizeJobJson(fields.metadata)
63
+ const result = sanitizeJobJson(fields.result)
64
+ const error = sanitizeError(fields.error)
65
+ return {
66
+ id: fields.id,
67
+ kind: fields.kind.slice(0, 128),
68
+ status: statusOf(record.state),
69
+ ...(progress == null ? {} : { progress }),
70
+ ...(fields.summary == null ? {} : { summary: fields.summary.slice(0, 2048) }),
71
+ ...(metadata == null || Array.isArray(metadata) || typeof metadata !== 'object'
72
+ ? {} : { metadata }),
73
+ ...(result === undefined ? {} : { result }),
74
+ ...(error == null ? {} : { error }),
75
+ cancellable: fields.cancellable ?? false,
76
+ createdAt,
77
+ updatedAt,
78
+ ...(record.startedAt == null ? {} : { startedAt: record.startedAt }),
79
+ ...(record.finishedAt == null ? {} : { finishedAt: record.finishedAt }),
80
+ }
81
+ }
82
+
83
+ const publicJobError = (type: string = 'job-failed'): PublicJobError => ({
84
+ type,
85
+ message: 'The background operation failed.',
86
+ })
87
+
88
+ return { sanitizeJobJson, jobViewOf, publicJobError }
89
+ }
90
+
91
+ export const jobViewHelper = createJobViewHelper()
@@ -0,0 +1,55 @@
1
+ import { describe, expect, test } from 'bun:test'
2
+ import { JobViewStatus } from '@owlmeans/job'
3
+ import { JobState } from '@owlmeans/queue'
4
+ import { jobViewHelper } from '../src/utils/view.js'
5
+
6
+ describe('@owlmeans/server-job — public projection boundary', () => {
7
+ test('maps only allowlisted fields and never copies a broker payload or raw failure', () => {
8
+ const view = jobViewHelper.jobViewOf({
9
+ id: 'broker-id', queue: 'private-lane', name: 'internal:build',
10
+ data: { accessToken: 'secret' }, error: 'stack and connection string',
11
+ state: JobState.Failed, progress: { percent: 65, secret: 'drop' },
12
+ createdAt: '2026-09-18T10:00:00.000Z', finishedAt: '2026-09-18T10:01:00.000Z',
13
+ }, {
14
+ id: 'opaque-id', kind: 'export', summary: 'Export failed',
15
+ error: jobViewHelper.publicJobError('export-failed'),
16
+ })
17
+
18
+ expect(view).toMatchObject({
19
+ id: 'opaque-id', kind: 'export', status: JobViewStatus.Failed,
20
+ progress: { percent: 65 }, error: {
21
+ type: 'export-failed', message: 'The background operation failed.',
22
+ },
23
+ })
24
+ expect(view).not.toHaveProperty('queue')
25
+ expect(view).not.toHaveProperty('name')
26
+ expect(view).not.toHaveProperty('data')
27
+ })
28
+
29
+ test('copies public JSON into bounded prototype-free values and drops executable data', () => {
30
+ const input = Object.create({ inherited: 'drop' }) as Record<string, unknown>
31
+ input.visible = { ok: true, fn: () => 'drop', infinity: Number.POSITIVE_INFINITY }
32
+ input.list = [1, undefined, Symbol('drop'), 'kept']
33
+
34
+ const sanitized = jobViewHelper.sanitizeJobJson(input) as Record<string, unknown>
35
+ expect(sanitized).toEqual({ visible: { ok: true }, list: [1, 'kept'] })
36
+ expect(Object.getPrototypeOf(sanitized)).toBeNull()
37
+ expect(sanitized).not.toHaveProperty('inherited')
38
+ })
39
+
40
+ test('caps public text before it reaches a serializer or a browser store', () => {
41
+ const view = jobViewHelper.jobViewOf({
42
+ id: 'raw', queue: 'lane', name: 'internal', state: JobState.Active,
43
+ progress: { message: 'm'.repeat(900) },
44
+ }, {
45
+ id: 'public', kind: 'k'.repeat(200), summary: 's'.repeat(3_000),
46
+ error: { type: 't'.repeat(200), message: 'e'.repeat(3_000) },
47
+ })
48
+
49
+ expect(view.kind).toHaveLength(128)
50
+ expect(view.summary).toHaveLength(2048)
51
+ expect(view.progress?.message).toHaveLength(512)
52
+ expect(view.error?.type).toHaveLength(128)
53
+ expect(view.error?.message).toHaveLength(2048)
54
+ })
55
+ })
package/build/consts.d.ts DELETED
@@ -1,26 +0,0 @@
1
- /**
2
- * The alias root a target app gets when its declaration names none, and the path segment the
3
- * group answers under.
4
- */
5
- export declare const DEFAULT_JOB_ROOT = "jobs";
6
- export declare const DEFAULT_JOB_PATH = "/jobs";
7
- /**
8
- * Where the owner is recorded inside a job's payload.
9
- *
10
- * A `JobRecord` has no owner column — the broker keeps only what the contract declares — so the
11
- * producer writes the subject into the job's own `data`, and every read here filters on
12
- * `data.<field>`. Change it per declaration when the app's payloads already name the subject
13
- * something else.
14
- */
15
- export declare const DEFAULT_OWNER_FIELD = "owner";
16
- /**
17
- * The socket event a `JobEvent` frame is pushed under.
18
- *
19
- * This name, and the `<root>:<verb>` alias shape in `entrypoints.ts`, are the whole contract
20
- * between this package and `@owlmeans/client-job` — the two halves cannot share a module without
21
- * dragging fastify into a browser bundle, so they each state it and the skills pin it.
22
- */
23
- export declare const JOB_EVENT = "job-event";
24
- /** Newest first: a job list is read to see what is happening now. */
25
- export declare const DEFAULT_JOB_SORT = "createdAt";
26
- //# sourceMappingURL=consts.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"consts.d.ts","sourceRoot":"","sources":["../src/consts.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,eAAO,MAAM,gBAAgB,SAAS,CAAA;AACtC,eAAO,MAAM,gBAAgB,UAAU,CAAA;AAEvC;;;;;;;GAOG;AACH,eAAO,MAAM,mBAAmB,UAAU,CAAA;AAE1C;;;;;;GAMG;AACH,eAAO,MAAM,SAAS,cAAc,CAAA;AAEpC,qEAAqE;AACrE,eAAO,MAAM,gBAAgB,cAAc,CAAA"}
package/build/consts.js DELETED
@@ -1,26 +0,0 @@
1
- /**
2
- * The alias root a target app gets when its declaration names none, and the path segment the
3
- * group answers under.
4
- */
5
- export const DEFAULT_JOB_ROOT = 'jobs';
6
- export const DEFAULT_JOB_PATH = '/jobs';
7
- /**
8
- * Where the owner is recorded inside a job's payload.
9
- *
10
- * A `JobRecord` has no owner column — the broker keeps only what the contract declares — so the
11
- * producer writes the subject into the job's own `data`, and every read here filters on
12
- * `data.<field>`. Change it per declaration when the app's payloads already name the subject
13
- * something else.
14
- */
15
- export const DEFAULT_OWNER_FIELD = 'owner';
16
- /**
17
- * The socket event a `JobEvent` frame is pushed under.
18
- *
19
- * This name, and the `<root>:<verb>` alias shape in `entrypoints.ts`, are the whole contract
20
- * between this package and `@owlmeans/client-job` — the two halves cannot share a module without
21
- * dragging fastify into a browser bundle, so they each state it and the skills pin it.
22
- */
23
- export const JOB_EVENT = 'job-event';
24
- /** Newest first: a job list is read to see what is happening now. */
25
- export const DEFAULT_JOB_SORT = 'createdAt';
26
- //# sourceMappingURL=consts.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"consts.js","sourceRoot":"","sources":["../src/consts.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,MAAM,CAAA;AACtC,MAAM,CAAC,MAAM,gBAAgB,GAAG,OAAO,CAAA;AAEvC;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,OAAO,CAAA;AAE1C;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,WAAW,CAAA;AAEpC,qEAAqE;AACrE,MAAM,CAAC,MAAM,gBAAgB,GAAG,WAAW,CAAA"}
@@ -1,20 +0,0 @@
1
- import type { JobEntrypointAliases, JobEntrypoints, JobEntrypointOptions } from './types.js';
2
- /**
3
- * The aliases one job group answers under.
4
- *
5
- * The shape — `<root>` and `<root>:<verb>` — is the contract `@owlmeans/client-job` addresses the
6
- * same group by, so a group renamed here is renamed there by passing the same root.
7
- */
8
- export declare const jobEntrypointAliases: (root: string) => JobEntrypointAliases;
9
- /**
10
- * Declare the list/get/cancel/watch entrypoints of one job group.
11
- *
12
- * It belongs in the SHARED package of a target app — the one both the API and the browser import —
13
- * so that the server binds and the client calls the very declarations, and neither side ever
14
- * writes a path. Declaring a second group is the same call with another root.
15
- *
16
- * The guard rides on the base alone: guards are inherited, so stating it once is what keeps the
17
- * four from drifting apart.
18
- */
19
- export declare const declareJobEntrypoints: (root: string, opts?: JobEntrypointOptions) => JobEntrypoints;
20
- //# sourceMappingURL=entrypoints.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"entrypoints.d.ts","sourceRoot":"","sources":["../src/entrypoints.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,oBAAoB,EAAE,cAAc,EAAE,oBAAoB,EAAgB,MAAM,YAAY,CAAA;AAE1G;;;;;GAKG;AACH,eAAO,MAAM,oBAAoB,SAAU,MAAM,KAAG,oBAMlD,CAAA;AAEF;;;;;;;;;GASG;AACH,eAAO,MAAM,qBAAqB,SAC1B,MAAM,SAAS,oBAAoB,KACxC,cA0BF,CAAA"}
@@ -1,46 +0,0 @@
1
- import { contract, openProtocol, protocol, typed } from '@owlmeans/entrypoint';
2
- import { backend, route, RouteMethod, socket } from '@owlmeans/route';
3
- import { DEFAULT_GUARD } from '@owlmeans/auth-common';
4
- import { DEFAULT_JOB_PATH } from './consts.js';
5
- import { JobListQuerySchema } from './schemas.js';
6
- /**
7
- * The aliases one job group answers under.
8
- *
9
- * The shape — `<root>` and `<root>:<verb>` — is the contract `@owlmeans/client-job` addresses the
10
- * same group by, so a group renamed here is renamed there by passing the same root.
11
- */
12
- export const jobEntrypointAliases = (root) => ({
13
- base: root,
14
- list: `${root}:list`,
15
- get: `${root}:get`,
16
- cancel: `${root}:cancel`,
17
- watch: `${root}:watch`,
18
- });
19
- /**
20
- * Declare the list/get/cancel/watch entrypoints of one job group.
21
- *
22
- * It belongs in the SHARED package of a target app — the one both the API and the browser import —
23
- * so that the server binds and the client calls the very declarations, and neither side ever
24
- * writes a path. Declaring a second group is the same call with another root.
25
- *
26
- * The guard rides on the base alone: guards are inherited, so stating it once is what keeps the
27
- * four from drifting apart.
28
- */
29
- export const declareJobEntrypoints = (root, opts) => {
30
- const aliases = jobEntrypointAliases(root);
31
- const base = {
32
- ...(opts?.parent != null ? { parent: opts.parent } : {}),
33
- ...(opts?.service != null ? { service: opts.service } : {}),
34
- };
35
- const guarded = opts?.guard === null ? undefined : { guards: opts?.guard ?? DEFAULT_GUARD };
36
- return {
37
- base: openProtocol(route(aliases.base, opts?.path ?? DEFAULT_JOB_PATH, backend(base)), guarded),
38
- list: protocol(route(aliases.list, '/', backend(aliases.base)), contract.request({ query: typed(JobListQuerySchema) }, typed())),
39
- // Static before parametric, so `/watch` is not swallowed by `/:id`. The router picks the
40
- // static branch on its own; the order here is for whoever reads the declaration.
41
- watch: protocol(route(aliases.watch, '/watch', socket(aliases.base)), contract(typed())),
42
- get: protocol(route(aliases.get, '/:id', backend(aliases.base)), contract.request({ params: typed() }, typed())),
43
- cancel: protocol(route(aliases.cancel, '/:id', backend(aliases.base, RouteMethod.DELETE)), contract.request({ params: typed() }, typed())),
44
- };
45
- };
46
- //# sourceMappingURL=entrypoints.js.map