dsh-hello 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +508 -2
  3. package/cordis.patch.yml +3 -0
  4. package/lib/catalogs.d.ts +100 -0
  5. package/lib/catalogs.d.ts.map +1 -0
  6. package/lib/catalogs.js +205 -0
  7. package/lib/catalogs.js.map +1 -0
  8. package/lib/client.js +544 -0
  9. package/lib/config.d.ts +96 -0
  10. package/lib/config.d.ts.map +1 -0
  11. package/lib/config.js +110 -0
  12. package/lib/config.js.map +1 -0
  13. package/lib/devices.d.ts +71 -0
  14. package/lib/devices.d.ts.map +1 -0
  15. package/lib/devices.js +219 -0
  16. package/lib/devices.js.map +1 -0
  17. package/lib/files.d.ts +43 -0
  18. package/lib/files.d.ts.map +1 -0
  19. package/lib/files.js +187 -0
  20. package/lib/files.js.map +1 -0
  21. package/lib/host.d.ts +324 -0
  22. package/lib/host.d.ts.map +1 -0
  23. package/lib/host.js +10 -0
  24. package/lib/host.js.map +1 -0
  25. package/lib/http.d.ts +77 -0
  26. package/lib/http.d.ts.map +1 -0
  27. package/lib/http.js +340 -0
  28. package/lib/http.js.map +1 -0
  29. package/lib/index.d.ts +20 -0
  30. package/lib/index.d.ts.map +1 -0
  31. package/lib/index.js +8227 -0
  32. package/lib/index.js.map +7 -0
  33. package/lib/interactions.d.ts +99 -0
  34. package/lib/interactions.d.ts.map +1 -0
  35. package/lib/interactions.js +568 -0
  36. package/lib/interactions.js.map +1 -0
  37. package/lib/pairing.d.ts +56 -0
  38. package/lib/pairing.d.ts.map +1 -0
  39. package/lib/pairing.js +128 -0
  40. package/lib/pairing.js.map +1 -0
  41. package/lib/protocol.d.ts +336 -0
  42. package/lib/protocol.d.ts.map +1 -0
  43. package/lib/protocol.js +7 -0
  44. package/lib/protocol.js.map +1 -0
  45. package/lib/push.d.ts +47 -0
  46. package/lib/push.d.ts.map +1 -0
  47. package/lib/push.js +339 -0
  48. package/lib/push.js.map +1 -0
  49. package/lib/read-state.d.ts +32 -0
  50. package/lib/read-state.d.ts.map +1 -0
  51. package/lib/read-state.js +39 -0
  52. package/lib/read-state.js.map +1 -0
  53. package/lib/routes.d.ts +33 -0
  54. package/lib/routes.d.ts.map +1 -0
  55. package/lib/routes.js +1293 -0
  56. package/lib/routes.js.map +1 -0
  57. package/lib/schedules.d.ts +31 -0
  58. package/lib/schedules.d.ts.map +1 -0
  59. package/lib/schedules.js +122 -0
  60. package/lib/schedules.js.map +1 -0
  61. package/lib/sessions.d.ts +60 -0
  62. package/lib/sessions.d.ts.map +1 -0
  63. package/lib/sessions.js +287 -0
  64. package/lib/sessions.js.map +1 -0
  65. package/lib/speech.d.ts +20 -0
  66. package/lib/speech.d.ts.map +1 -0
  67. package/lib/speech.js +47 -0
  68. package/lib/speech.js.map +1 -0
  69. package/lib/streams.d.ts +30 -0
  70. package/lib/streams.d.ts.map +1 -0
  71. package/lib/streams.js +106 -0
  72. package/lib/streams.js.map +1 -0
  73. package/lib/terminal.d.ts +55 -0
  74. package/lib/terminal.d.ts.map +1 -0
  75. package/lib/terminal.js +231 -0
  76. package/lib/terminal.js.map +1 -0
  77. package/lib/util.d.ts +18 -0
  78. package/lib/util.d.ts.map +1 -0
  79. package/lib/util.js +52 -0
  80. package/lib/util.js.map +1 -0
  81. package/lib/version.d.ts +15 -0
  82. package/lib/version.d.ts.map +1 -0
  83. package/lib/version.js +98 -0
  84. package/lib/version.js.map +1 -0
  85. package/package.json +80 -4
package/lib/config.js ADDED
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Plugin configuration. Every tunable value is a configuration field so a
3
+ * deployment can change it from `cordis.yml` without editing code.
4
+ */
5
+ import Schema from '@deepseek-ai/schemastery';
6
+ export const Config = Schema.object({
7
+ basePath: Schema.string().default('/dsh-door'),
8
+ allowedHosts: Schema.array(Schema.string()).default([]),
9
+ requireSecure: Schema.boolean().default(false),
10
+ strictHostCheck: Schema.boolean().default(false),
11
+ pairingTtlMs: Schema.number().default(5 * 60 * 1000),
12
+ pairingCodeLength: Schema.number().default(4),
13
+ pairingMaxAttempts: Schema.number().default(8),
14
+ pairingCode: Schema.string(),
15
+ logPairingCode: Schema.boolean().default(true),
16
+ approvalWaitTimeoutMs: Schema.number().default(2 * 60 * 1000),
17
+ questionWaitTimeoutMs: Schema.number().default(2 * 60 * 1000),
18
+ allowSessionWideGrants: Schema.boolean().default(true),
19
+ enableDebugRoutes: Schema.boolean().default(false),
20
+ maxBodyBytes: Schema.number().default(64 * 1024),
21
+ rateLimitWindowMs: Schema.number().default(60 * 1000),
22
+ rateLimitMax: Schema.number().default(240),
23
+ /**
24
+ * @deprecated 0.2.2 — 0.2.1 fallback only; the default floor moves to 0.2.2.
25
+ * @since 0.2.1
26
+ */
27
+ dshVersionRange: Schema.string().default('>=0.2.1-rc.4 <0.3.0'),
28
+ push: Schema.object({
29
+ provider: Schema.union(['none', 'fcm', 'apns', 'relay']).default('none'),
30
+ relayUrl: Schema.string(),
31
+ relayHostToken: Schema.string(),
32
+ fcmServiceAccountJson: Schema.string(),
33
+ fcmProjectId: Schema.string(),
34
+ apnsKey: Schema.string(),
35
+ apnsKeyId: Schema.string(),
36
+ apnsTeamId: Schema.string(),
37
+ apnsTopic: Schema.string(),
38
+ apnsEnvironment: Schema.union(['sandbox', 'production']).default('production'),
39
+ notifyTurnEnd: Schema.boolean().default(true),
40
+ notifyApproval: Schema.boolean().default(true),
41
+ notifyQuestion: Schema.boolean().default(true),
42
+ }).default({}),
43
+ });
44
+ /** Structural type check for the configuration Cordis passes to apply(). */
45
+ export function normalizeConfig(input) {
46
+ const raw = (input ?? {});
47
+ const push = { ...(raw.push ?? {}) };
48
+ const config = {
49
+ basePath: normalizeBasePath(raw.basePath ?? '/dsh-door'),
50
+ allowedHosts: (raw.allowedHosts ?? []).map(value => value.trim().toLowerCase()).filter(Boolean),
51
+ requireSecure: raw.requireSecure ?? false,
52
+ strictHostCheck: raw.strictHostCheck ?? false,
53
+ pairingTtlMs: raw.pairingTtlMs ?? 5 * 60 * 1000,
54
+ pairingCodeLength: raw.pairingCodeLength ?? 4,
55
+ pairingMaxAttempts: raw.pairingMaxAttempts ?? 8,
56
+ logPairingCode: raw.logPairingCode ?? true,
57
+ approvalWaitTimeoutMs: raw.approvalWaitTimeoutMs ?? 2 * 60 * 1000,
58
+ questionWaitTimeoutMs: raw.questionWaitTimeoutMs ?? 2 * 60 * 1000,
59
+ allowSessionWideGrants: raw.allowSessionWideGrants ?? true,
60
+ enableDebugRoutes: raw.enableDebugRoutes ?? false,
61
+ maxBodyBytes: raw.maxBodyBytes ?? 64 * 1024,
62
+ rateLimitWindowMs: raw.rateLimitWindowMs ?? 60 * 1000,
63
+ rateLimitMax: raw.rateLimitMax ?? 240,
64
+ dshVersionRange: raw.dshVersionRange ?? '>=0.2.1-rc.4 <0.3.0',
65
+ push: {
66
+ provider: push.provider ?? 'none',
67
+ relayUrl: push.relayUrl,
68
+ relayHostToken: push.relayHostToken,
69
+ fcmServiceAccountJson: push.fcmServiceAccountJson,
70
+ fcmProjectId: push.fcmProjectId,
71
+ apnsKey: push.apnsKey,
72
+ apnsKeyId: push.apnsKeyId,
73
+ apnsTeamId: push.apnsTeamId,
74
+ apnsTopic: push.apnsTopic,
75
+ apnsEnvironment: push.apnsEnvironment ?? 'production',
76
+ notifyTurnEnd: push.notifyTurnEnd ?? true,
77
+ notifyApproval: push.notifyApproval ?? true,
78
+ notifyQuestion: push.notifyQuestion ?? true,
79
+ },
80
+ };
81
+ if (raw.pairingCode !== undefined)
82
+ config.pairingCode = raw.pairingCode;
83
+ if (!Number.isFinite(config.pairingTtlMs) || config.pairingTtlMs < 1000) {
84
+ throw new Error('dsh-door: pairing.ttlMs must be at least 1000 ms');
85
+ }
86
+ if (!Number.isInteger(config.pairingCodeLength) || config.pairingCodeLength < 4 || config.pairingCodeLength > 32) {
87
+ throw new Error('dsh-door: pairing.codeLength must be an integer from 4 to 32');
88
+ }
89
+ if (!Number.isFinite(config.maxBodyBytes) || config.maxBodyBytes < 1024) {
90
+ throw new Error('dsh-door: maxBodyBytes must be at least 1024');
91
+ }
92
+ return config;
93
+ }
94
+ function normalizeBasePath(value) {
95
+ const trimmed = value.trim();
96
+ if (!trimmed.startsWith('/'))
97
+ throw new Error('dsh-door: basePath must start with "/"');
98
+ const withoutTrailing = trimmed.replace(/\/+$/, '');
99
+ if (withoutTrailing.length === 0)
100
+ throw new Error('dsh-door: basePath may not be "/"');
101
+ return withoutTrailing;
102
+ }
103
+ export const defaultPushConfig = {
104
+ provider: 'none',
105
+ apnsEnvironment: 'production',
106
+ notifyTurnEnd: true,
107
+ notifyApproval: true,
108
+ notifyQuestion: true,
109
+ };
110
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,MAAM,MAAM,0BAA0B,CAAA;AA0F7C,MAAM,CAAC,MAAM,MAAM,GAAmB,MAAM,CAAC,MAAM,CAAC;IAClD,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC,WAAW,CAAC;IAC9C,YAAY,EAAE,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,OAAO,CAAC,EAAE,CAAC;IACvD,aAAa,EAAE,MAAM,CAAC,OAAO,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC;IAC9C,eAAe,EAAE,MAAM,CAAC,OAAO,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC;IAChD,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC;IACpD,iBAAiB,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC;IAC7C,kBAAkB,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,O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ostContext } from './host.js';
2
+ export type PushKind = 'approval' | 'question' | 'turn-end';
3
+ export interface PushSubscriptions {
4
+ approval: boolean;
5
+ question: boolean;
6
+ turnEnd: boolean;
7
+ }
8
+ export declare const DEFAULT_PUSH_SUBSCRIPTIONS: PushSubscriptions;
9
+ export interface DevicePushRegistration {
10
+ provider: 'fcm' | 'apns';
11
+ token: string;
12
+ updatedAt: number;
13
+ }
14
+ export interface DevicePushTarget extends DevicePushRegistration {
15
+ deviceId: string;
16
+ }
17
+ /** Public device view used by the app; never includes the token hash. */
18
+ export interface DeviceView {
19
+ deviceId: string;
20
+ deviceName: string;
21
+ platform?: string;
22
+ appVersion?: string;
23
+ pairedAt: number;
24
+ lastSeenAt: number;
25
+ authorities: string[];
26
+ subscriptions: PushSubscriptions;
27
+ push?: DevicePushRegistration;
28
+ }
29
+ /**
30
+ * Durable device registry. Records live in the dsh credential store as one
31
+ * owner-scoped grant record, so device tokens never enter configuration files
32
+ * and survive a Host restart.
33
+ */
34
+ export declare class DeviceStore {
35
+ private readonly ctx;
36
+ private readonly credentials;
37
+ private readonly devices;
38
+ private readonly byTokenHash;
39
+ private loaded;
40
+ private writeQueue;
41
+ constructor(ctx: HostContext, credentials: CredentialProviderService | undefined);
42
+ load(): Promise<void>;
43
+ list(): DeviceView[];
44
+ count(): number;
45
+ findById(deviceId: string): DeviceView | undefined;
46
+ /** Resolve a bearer token to its device and update last-seen time. */
47
+ authenticate(token: string): DeviceView | undefined;
48
+ pair(input: {
49
+ token: string;
50
+ deviceName: string;
51
+ devicePublicKey?: string;
52
+ platform?: string;
53
+ appVersion?: string;
54
+ authority: string;
55
+ }): Promise<DeviceView>;
56
+ addAuthority(deviceId: string, authority: string): Promise<void>;
57
+ revoke(deviceId: string): Promise<boolean>;
58
+ /** Rename a paired device without changing its token or pairing. */
59
+ rename(deviceId: string, name: string): Promise<boolean>;
60
+ setPush(deviceId: string, push: DevicePushRegistration): Promise<boolean>;
61
+ setSubscriptions(deviceId: string, subscriptions: PushSubscriptions): Promise<boolean>;
62
+ clearPush(deviceId: string): Promise<void>;
63
+ /** Registered devices that opted into this notification kind. */
64
+ pushDevices(kind: PushKind): DevicePushTarget[];
65
+ /** Devices that carry an outbound push registration for one provider. */
66
+ pushTargets(provider: 'fcm' | 'apns', kind: PushKind): DevicePushRegistration[];
67
+ private remember;
68
+ private schedulePersist;
69
+ private persist;
70
+ }
71
+ //# sourceMappingURL=devices.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"devices.d.ts","sourceRoot":"","sources":["../src/devices.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,yBAAyB,EAAE,WAAW,EAAE,MAAM,WAAW,CAAA;AAMvE,MAAM,MAAM,QAAQ,GAAG,UAAU,GAAG,UAAU,GAAG,UAAU,CAAA;AAE3D,MAAM,WAAW,iBAAiB;IAChC,QAAQ,EAAE,OAAO,CAAA;IACjB,QAAQ,EAAE,OAAO,CAAA;IACjB,OAAO,EAAE,OAAO,CAAA;CACjB;AAED,eAAO,MAAM,0BAA0B,EAAE,iBAIxC,CAAA;AAED,MAAM,WAAW,sBAAsB;IACrC,QAAQ,EAAE,KAAK,GAAG,MAAM,CAAA;IACxB,KAAK,EAAE,MAAM,CAAA;IACb,SAAS,EAAE,MAAM,CAAA;CAClB;AAED,MAAM,WAAW,gBAAiB,SAAQ,sBAAsB;IAC9D,QAAQ,EAAE,MAAM,CAAA;CACjB;AAoBD,yEAAyE;AACzE,MAAM,WAAW,UAAU;IACzB,QAAQ,EAAE,MAAM,CAAA;IAChB,UAAU,EAAE,MAAM,CAAA;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,QAAQ,EAAE,MAAM,CAAA;IAChB,UAAU,EAAE,MAAM,CAAA;IAClB,WAAW,EAAE,MAAM,EAAE,CAAA;IACrB,aAAa,EAAE,iBAAiB,CAAA;IAChC,IAAI,CAAC,EAAE,sBAAsB,CAAA;CAC9B;A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AAM,EAAE,aAAa,EAAE,iBAAiB,GAAG,OAAO,CAAC,OAAO,CAAC;IAQtF,SAAS,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAOhD,iEAAiE;IACjE,WAAW,CAAC,IAAI,EAAE,QAAQ,GAAG,gBAAgB,EAAE;IAM/C,yEAAyE;IACzE,WAAW,CAAC,QAAQ,EAAE,KAAK,GAAG,MAAM,EAAE,IAAI,EAAE,QAAQ,GAAG,sBAAsB,EAAE;IAI/E,OAAO,CAAC,QAAQ;IAKhB,OAAO,CAAC,eAAe;IAMvB,OAAO,CAAC,OAAO;CAahB"}
package/lib/devices.js ADDED
@@ -0,0 +1,219 @@
1
+ import { fingerprint, safeEqual, sha256 } from './util.js';
2
+ /** Credential record key owned by this plugin. */
3
+ const DEVICE_RECORD_KEY = 'dsh-door/devices';
4
+ export const DEFAULT_PUSH_SUBSCRIPTIONS = {
5
+ approval: true,
6
+ question: true,
7
+ turnEnd: true,
8
+ };
9
+ /**
10
+ * Durable device registry. Records live in the dsh credential store as one
11
+ * owner-scoped grant record, so device tokens never enter configuration files
12
+ * and survive a Host restart.
13
+ */
14
+ export class DeviceStore {
15
+ ctx;
16
+ credentials;
17
+ devices = new Map();
18
+ byTokenHash = new Map();
19
+ loaded = false;
20
+ writeQueue = Promise.resolve();
21
+ constructor(ctx, credentials) {
22
+ this.ctx = ctx;
23
+ this.credentials = credentials;
24
+ }
25
+ async load() {
26
+ if (this.loaded)
27
+ return;
28
+ if (this.credentials === undefined) {
29
+ throw new Error('dsh-door: this deployment composes no credential store. ' +
30
+ 'Load @deepseek-ai/dsh-credentials-local so paired devices can be stored durably.');
31
+ }
32
+ const record = await this.credentials.readRecord(DEVICE_RECORD_KEY);
33
+ const payload = record?.payload;
34
+ if (isDeviceFile(payload)) {
35
+ for (const device of payload.devices)
36
+ this.remember(device);
37
+ }
38
+ this.loaded = true;
39
+ }
40
+ list() {
41
+ return [...this.devices.values()]
42
+ .sort((a, b) => b.pairedAt - a.pairedAt)
43
+ .map(toView);
44
+ }
45
+ count() {
46
+ return this.devices.size;
47
+ }
48
+ findById(deviceId) {
49
+ const device = this.devices.get(deviceId);
50
+ return device === undefined ? undefined : toView(device);
51
+ }
52
+ /** Resolve a bearer token to its device and update last-seen time. */
53
+ authenticate(token) {
54
+ const hash = sha256(token);
55
+ const device = this.byTokenHash.get(hash);
56
+ if (device === undefined)
57
+ return undefined;
58
+ if (!safeEqual(device.tokenHash, hash))
59
+ return undefined;
60
+ const now = Date.now();
61
+ const stale = now - device.lastSeenAt > 5 * 60 * 1000;
62
+ device.lastSeenAt = now;
63
+ // last-seen is a hint, not a per-request audit record; persist at most
64
+ // once per five minutes per device to avoid rewriting the credential file
65
+ // on every poll.
66
+ if (stale)
67
+ this.schedulePersist();
68
+ return toView(device);
69
+ }
70
+ async pair(input) {
71
+ const deviceId = input.devicePublicKey === undefined
72
+ ? fingerprint(input.token)
73
+ : fingerprint(input.devicePublicKey);
74
+ const existing = this.devices.get(deviceId);
75
+ const now = Date.now();
76
+ if (existing !== undefined) {
77
+ existing.tokenHash = sha256(input.token);
78
+ existing.deviceName = input.deviceName;
79
+ if (input.platform === undefined)
80
+ delete existing.platform;
81
+ else
82
+ existing.platform = input.platform;
83
+ if (input.appVersion === undefined)
84
+ delete existing.appVersion;
85
+ else
86
+ existing.appVersion = input.appVersion;
87
+ existing.lastSeenAt = now;
88
+ existing.authorities = unique([...existing.authorities, input.authority]);
89
+ this.byTokenHash.set(existing.tokenHash, existing);
90
+ await this.persist();
91
+ return toView(existing);
92
+ }
93
+ const device = {
94
+ deviceId,
95
+ tokenHash: sha256(input.token),
96
+ deviceName: input.deviceName,
97
+ ...(input.platform === undefined ? {} : { platform: input.platform }),
98
+ ...(input.appVersion === undefined ? {} : { appVersion: input.appVersion }),
99
+ pairedAt: now,
100
+ lastSeenAt: now,
101
+ authorities: [input.authority],
102
+ };
103
+ this.remember(device);
104
+ await this.persist();
105
+ return toView(device);
106
+ }
107
+ async addAuthority(deviceId, authority) {
108
+ const device = this.devices.get(deviceId);
109
+ if (device === undefined)
110
+ return;
111
+ if (!device.authorities.includes(authority)) {
112
+ device.authorities = [...device.authorities, authority];
113
+ await this.persist();
114
+ }
115
+ }
116
+ async revoke(deviceId) {
117
+ const device = this.devices.get(deviceId);
118
+ if (device === undefined)
119
+ return false;
120
+ this.devices.delete(deviceId);
121
+ this.byTokenHash.delete(device.tokenHash);
122
+ await this.persist();
123
+ return true;
124
+ }
125
+ /** Rename a paired device without changing its token or pairing. */
126
+ async rename(deviceId, name) {
127
+ const device = this.devices.get(deviceId);
128
+ if (device === undefined)
129
+ return false;
130
+ device.deviceName = name;
131
+ await this.persist();
132
+ return true;
133
+ }
134
+ async setPush(deviceId, push) {
135
+ const device = this.devices.get(deviceId);
136
+ if (device === undefined)
137
+ return false;
138
+ device.push = push;
139
+ await this.persist();
140
+ return true;
141
+ }
142
+ async setSubscriptions(deviceId, subscriptions) {
143
+ const device = this.devices.get(deviceId);
144
+ if (device === undefined)
145
+ return false;
146
+ device.subscriptions = { ...subscriptions };
147
+ await this.persist();
148
+ return true;
149
+ }
150
+ async clearPush(deviceId) {
151
+ const device = this.devices.get(deviceId);
152
+ if (device === undefined)
153
+ return;
154
+ delete device.push;
155
+ await this.persist();
156
+ }
157
+ /** Registered devices that opted into this notification kind. */
158
+ pushDevices(kind) {
159
+ return [...this.devices.values()]
160
+ .filter(device => device.push !== undefined && subscriptionsOf(device)[subscriptionKey(kind)])
161
+ .map(device => ({ ...device.push, deviceId: device.deviceId }));
162
+ }
163
+ /** Devices that carry an outbound push registration for one provider. */
164
+ pushTargets(provider, kind) {
165
+ return this.pushDevices(kind).filter(push => push.provider === provider);
166
+ }
167
+ remember(device) {
168
+ this.devices.set(device.deviceId, device);
169
+ this.byTokenHash.set(device.tokenHash, device);
170
+ }
171
+ schedulePersist() {
172
+ // lastSeenAt is best effort; a failed write must not fail an otherwise
173
+ // authenticated request.
174
+ void this.persist().catch(() => undefined);
175
+ }
176
+ persist() {
177
+ this.writeQueue = this.writeQueue
178
+ .catch(() => undefined)
179
+ .then(async () => {
180
+ if (this.credentials === undefined)
181
+ return;
182
+ const file = { version: 1, devices: [...this.devices.values()] };
183
+ await this.credentials.modifyRecord(DEVICE_RECORD_KEY, async () => ({
184
+ kind: 'grant',
185
+ payload: file,
186
+ }));
187
+ });
188
+ return this.writeQueue;
189
+ }
190
+ }
191
+ function isDeviceFile(value) {
192
+ if (typeof value !== 'object' || value === null)
193
+ return false;
194
+ const candidate = value;
195
+ return candidate.version === 1 && Array.isArray(candidate.devices);
196
+ }
197
+ function subscriptionsOf(device) {
198
+ return { ...DEFAULT_PUSH_SUBSCRIPTIONS, ...device.subscriptions };
199
+ }
200
+ function subscriptionKey(kind) {
201
+ return kind === 'turn-end' ? 'turnEnd' : kind;
202
+ }
203
+ function toView(device) {
204
+ return {
205
+ deviceId: device.deviceId,
206
+ deviceName: device.deviceName,
207
+ platform: device.platform,
208
+ appVersion: device.appVersion,
209
+ pairedAt: device.pairedAt,
210
+ lastSeenAt: device.lastSeenAt,
211
+ authorities: [...device.authorities],
212
+ subscriptions: subscriptionsOf(device),
213
+ push: device.push,
214
+ };
215
+ }
216
+ function unique(values) {
217
+ return [...new Set(values)];
218
+ }
219
+ //# sourceMappingURL=devices.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"devices.js","sourceRoot":"","sources":["../src/devices.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,WAAW,CAAA;AAE1D,kDAAkD;AAClD,MAAM,iBAAiB,GAAG,kBAA6B,CAAA;AAUvD,MAAM,CAAC,MAAM,0BAA0B,GAAsB;IAC3D,QAAQ,EAAE,IAAI;IACd,QAAQ,EAAE,IAAI;IACd,OAAO,EAAE,IAAI;CACd,CAAA;AA2CD;;;;GAIG;AACH,MAAM,OAAO,WAAW;IAOH;IACA;IAPF,OAAO,GAAG,IAAI,GAAG,EAAwB,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AC7D,MAAM,SAAS,GAAG,KAA4B,CAAA;IAC9C,OAAO,SAAS,CAAC,OAAO,KAAK,CAAC,IAAI,KAAK,CAAC,OAAO,CAAC,SAAS,CAAC,OAAO,CAAC,CAAA;AACpE,CAAC;AAED,SAAS,eAAe,CAAC,MAAoB;IAC3C,OAAO,EAAE,GAAG,0BAA0B,EAAE,GAAG,MAAM,CAAC,aAAa,EAAE,CAAA;AACnE,CAAC;AAED,SAAS,eAAe,CAAC,IAAc;IACrC,OAAO,IAAI,KAAK,UAAU,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAA;AAC/C,CAAC;AAED,SAAS,MAAM,CAAC,MAAoB;IAClC,OAAO;QACL,QAAQ,EAAE,MAAM,CAAC,QAAQ;QACzB,UAAU,EAAE,MAAM,CAAC,UAAU;QAC7B,QAAQ,EAAE,MAAM,CAAC,QAAQ;QACzB,UAAU,EAAE,MAAM,CAAC,UAAU;QAC7B,QAAQ,EAAE,MAAM,CAAC,QAAQ;QACzB,UAAU,EAAE,MAAM,CAAC,UAAU;QAC7B,WAAW,EAAE,CAAC,GAAG,MAAM,CAAC,WAAW,CAAC;QACpC,aAAa,EAAE,eAAe,CAAC,MAAM,CAAC;QACtC,IAAI,EAAE,MAAM,CAAC,IAAI;KAClB,CAAA;AACH,CAAC;AAED,SAAS,MAAM,CAAC,MAAgB;IAC9B,OAAO,CAAC,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC,CAAA;AAC7B,CAAC"}
package/lib/files.d.ts ADDED
@@ -0,0 +1,43 @@
1
+ import type { HostContext } from './host.js';
2
+ export interface WorkspaceFileEntry {
3
+ name: string;
4
+ path: string;
5
+ kind: 'directory' | 'file';
6
+ size?: number;
7
+ modifiedAt?: number;
8
+ }
9
+ export interface WorkspaceFileList {
10
+ root: string;
11
+ path: string;
12
+ entries: WorkspaceFileEntry[];
13
+ truncated: boolean;
14
+ }
15
+ export interface WorkspaceFileContent {
16
+ path: string;
17
+ size: number;
18
+ /** Byte offset this chunk starts at. */
19
+ offset: number;
20
+ /** True when more bytes remain after this chunk. */
21
+ truncated: boolean;
22
+ /** Byte offset to request next, when truncated. */
23
+ nextOffset?: number;
24
+ content: string;
25
+ }
26
+ /** List one directory without activating the Session or following symlinks. */
27
+ export declare function listWorkspaceFiles(ctx: HostContext, sessionId: string, requestedPath: string, signal: AbortSignal): Promise<WorkspaceFileList>;
28
+ /** List a Workspace directory without needing a Session (the file browser entry). */
29
+ export declare function listWorkspaceFilesByWorkspace(ctx: HostContext, workspaceId: string, requestedPath: string, signal: AbortSignal): Promise<WorkspaceFileList>;
30
+ /** Read at most 256 KiB of a UTF-8 text file inside the Session cwd, optionally from a byte offset. */
31
+ export declare function readWorkspaceFile(ctx: HostContext, sessionId: string, requestedPath: string, signal: AbortSignal, offset?: number): Promise<WorkspaceFileContent>;
32
+ /** Read a Workspace file without needing a Session. */
33
+ export declare function readWorkspaceFileByWorkspace(ctx: HostContext, workspaceId: string, requestedPath: string, signal: AbortSignal, offset?: number): Promise<WorkspaceFileContent>;
34
+ /** Resolve one file for binary download (documents, images) without reading it as text. */
35
+ export declare function resolveWorkspaceBinary(ctx: HostContext, scope: {
36
+ workspaceId?: string;
37
+ sessionId?: string;
38
+ }, requestedPath: string, signal: AbortSignal): Promise<{
39
+ filename: string;
40
+ size: number;
41
+ contentType: string;
42
+ }>;
43
+ //# sourceMappingURL=files.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"files.d.ts","sourceRoot":"","sources":["../src/files.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,WAAW,CAAA;AAM5C,MAAM,WAAW,kBAAkB;IACjC,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,EAAE,WAAW,GAAG,MAAM,CAAA;IAC1B,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,UAAU,CAAC,EAAE,MAAM,CAAA;CACpB;AAED,MA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W,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAA;CAAE,EACnD,aAAa,EAAE,MAAM,EACrB,MAAM,EAAE,WAAW,GAClB,OAAO,CAAC;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAA;CAAE,CAAC,CAQlE"}
package/lib/files.js ADDED
@@ -0,0 +1,187 @@
1
+ import { open, readdir, realpath, stat } from 'node:fs/promises';
2
+ import { isAbsolute, relative, resolve, sep } from 'node:path';
3
+ import { HttpError } from './http.js';
4
+ const MAX_ENTRIES = 300;
5
+ const MAX_FILE_BYTES = 256 * 1024;
6
+ /** List one directory without activating the Session or following symlinks. */
7
+ export async function listWorkspaceFiles(ctx, sessionId, requestedPath, signal) {
8
+ return listDirectory(ctx, await workspaceRoot(ctx, sessionId, signal), requestedPath);
9
+ }
10
+ /** List a Workspace directory without needing a Session (the file browser entry). */
11
+ export async function listWorkspaceFilesByWorkspace(ctx, workspaceId, requestedPath, signal) {
12
+ return listDirectory(ctx, await workspaceRootById(ctx, workspaceId), requestedPath);
13
+ }
14
+ async function listDirectory(ctx, root, requestedPath) {
15
+ const { root: rootPath, rootReal } = root;
16
+ const directory = await confinedRealPath(rootReal, requestedPath);
17
+ const info = await stat(directory);
18
+ if (!info.isDirectory())
19
+ throw new HttpError(400, 'not-a-directory', 'the requested path is not a directory');
20
+ const dirents = await readdir(directory, { withFileTypes: true });
21
+ const visible = dirents.filter(entry => entry.isDirectory() || entry.isFile());
22
+ visible.sort((a, b) => {
23
+ if (a.isDirectory() !== b.isDirectory())
24
+ return a.isDirectory() ? -1 : 1;
25
+ return a.name.localeCompare(b.name);
26
+ });
27
+ const entries = await Promise.all(visible.slice(0, MAX_ENTRIES).map(async (entry) => {
28
+ const absolute = resolve(directory, entry.name);
29
+ const entryInfo = await stat(absolute);
30
+ const path = displayPath(rootReal, absolute);
31
+ return entry.isDirectory()
32
+ ? { name: entry.name, path, kind: 'directory' }
33
+ : { name: entry.name, path, kind: 'file', size: entryInfo.size, modifiedAt: entryInfo.mtimeMs };
34
+ }));
35
+ return { root: rootPath, path: displayPath(rootReal, directory), entries, truncated: visible.length > MAX_ENTRIES };
36
+ }
37
+ /** Read at most 256 KiB of a UTF-8 text file inside the Session cwd, optionally from a byte offset. */
38
+ export async function readWorkspaceFile(ctx, sessionId, requestedPath, signal, offset = 0) {
39
+ return readFileAt(await workspaceRoot(ctx, sessionId, signal), requestedPath, offset);
40
+ }
41
+ /** Read a Workspace file without needing a Session. */
42
+ export async function readWorkspaceFileByWorkspace(ctx, workspaceId, requestedPath, signal, offset = 0) {
43
+ return readFileAt(await workspaceRootById(ctx, workspaceId), requestedPath, offset);
44
+ }
45
+ async function readFileAt(root, requestedPath, offset) {
46
+ const { rootReal } = root;
47
+ const filename = await confinedRealPath(rootReal, requestedPath);
48
+ const info = await stat(filename);
49
+ if (!info.isFile())
50
+ throw new HttpError(400, 'not-a-file', 'the requested path is not a regular file');
51
+ if (!Number.isSafeInteger(offset) || offset < 0 || offset > info.size) {
52
+ throw new HttpError(400, 'invalid-offset', 'offset must be a byte position inside the file');
53
+ }
54
+ const handle = await open(filename, 'r');
55
+ try {
56
+ const remaining = info.size - offset;
57
+ const length = Math.min(remaining, MAX_FILE_BYTES);
58
+ const buffer = Buffer.alloc(length);
59
+ const { bytesRead } = length === 0 ? { bytesRead: 0 } : await handle.read(buffer, 0, length, offset);
60
+ const bytes = buffer.subarray(0, bytesRead);
61
+ // A NUL is a conservative binary guard: source/text files do not contain
62
+ // it, and sending arbitrary binary as JSON would make the phone unusable.
63
+ if (bytes.includes(0))
64
+ throw new HttpError(415, 'binary-file', 'binary files cannot be previewed as text');
65
+ // Do not split a UTF-8 sequence across chunks; the dropped bytes are read
66
+ // again from the next offset.
67
+ const contentBytes = trimIncompleteUtf8(bytes);
68
+ const nextOffset = offset + contentBytes.length < info.size ? offset + contentBytes.length : undefined;
69
+ return {
70
+ path: displayPath(rootReal, filename),
71
+ size: info.size,
72
+ offset,
73
+ truncated: nextOffset !== undefined,
74
+ ...(nextOffset === undefined ? {} : { nextOffset }),
75
+ content: contentBytes.toString('utf8'),
76
+ };
77
+ }
78
+ finally {
79
+ await handle.close();
80
+ }
81
+ }
82
+ /** Drop a trailing partial UTF-8 sequence so each chunk decodes cleanly. */
83
+ function trimIncompleteUtf8(bytes) {
84
+ const length = bytes.length;
85
+ if (length === 0)
86
+ return bytes;
87
+ let start = length - 1;
88
+ while (start >= 0 && (bytes[start] & 0xC0) === 0x80)
89
+ start--;
90
+ if (start < 0)
91
+ return bytes;
92
+ const lead = bytes[start];
93
+ const expected = lead >= 0xF0 ? 4 : lead >= 0xE0 ? 3 : lead >= 0xC0 ? 2 : 1;
94
+ if (expected === 1)
95
+ return bytes;
96
+ return length - start < expected ? bytes.subarray(0, start) : bytes;
97
+ }
98
+ /** Resolve one file for binary download (documents, images) without reading it as text. */
99
+ export async function resolveWorkspaceBinary(ctx, scope, requestedPath, signal) {
100
+ const root = scope.workspaceId !== undefined
101
+ ? await workspaceRootById(ctx, scope.workspaceId)
102
+ : await workspaceRoot(ctx, scope.sessionId ?? '', signal);
103
+ const filename = await confinedRealPath(root.rootReal, requestedPath);
104
+ const info = await stat(filename);
105
+ if (!info.isFile())
106
+ throw new HttpError(400, 'not-a-file', 'the requested path is not a regular file');
107
+ return { filename, size: info.size, contentType: contentTypeFor(filename) };
108
+ }
109
+ const MIME_TYPES = {
110
+ pdf: 'application/pdf',
111
+ docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
112
+ rtf: 'application/rtf',
113
+ pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
114
+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
115
+ xls: 'application/vnd.ms-excel',
116
+ xlsm: 'application/vnd.ms-excel.sheet.macroEnabled.12',
117
+ ods: 'application/vnd.oasis.opendocument.spreadsheet',
118
+ csv: 'text/csv',
119
+ tsv: 'text/tab-separated-values',
120
+ png: 'image/png',
121
+ jpg: 'image/jpeg',
122
+ jpeg: 'image/jpeg',
123
+ gif: 'image/gif',
124
+ webp: 'image/webp',
125
+ svg: 'image/svg+xml',
126
+ };
127
+ function contentTypeFor(filename) {
128
+ const ext = filename.slice(filename.lastIndexOf('.') + 1).toLowerCase();
129
+ return MIME_TYPES[ext] ?? 'application/octet-stream';
130
+ }
131
+ async function workspaceRoot(ctx, sessionId, signal) {
132
+ const list = await ctx.sessionController.list({}, signal);
133
+ const session = list.items.find(item => item.sessionId === sessionId);
134
+ if (session === undefined)
135
+ throw new HttpError(404, 'session-not-found', 'the Session does not exist');
136
+ if (session.cwd === undefined || session.cwd.trim().length === 0) {
137
+ throw new HttpError(409, 'workspace-unavailable', 'this Session has no working directory');
138
+ }
139
+ return sessionRoot(session.cwd);
140
+ }
141
+ /** Resolve a Workspace path from the registry, so files do not need a Session. */
142
+ async function workspaceRootById(ctx, workspaceId) {
143
+ const registry = ctx.get('workspaceRegistry');
144
+ const workspace = registry?.get?.(workspaceId);
145
+ if (workspace === undefined) {
146
+ throw new HttpError(404, 'workspace-not-found', 'the Workspace does not exist');
147
+ }
148
+ const path = typeof workspace.path === 'string' ? workspace.path : '';
149
+ if (path.trim().length === 0) {
150
+ throw new HttpError(409, 'workspace-unavailable', 'this Workspace has no directory');
151
+ }
152
+ return sessionRoot(path);
153
+ }
154
+ async function sessionRoot(directory) {
155
+ try {
156
+ return { root: directory, rootReal: await realpath(directory) };
157
+ }
158
+ catch {
159
+ throw new HttpError(404, 'workspace-not-found', 'the Workspace directory does not exist');
160
+ }
161
+ }
162
+ async function confinedRealPath(rootReal, requestedPath) {
163
+ if (requestedPath.includes('\0'))
164
+ throw new HttpError(400, 'invalid-path', 'the path contains a NUL byte');
165
+ const candidate = resolve(rootReal, requestedPath);
166
+ if (!inside(rootReal, candidate))
167
+ throw new HttpError(403, 'path-outside-workspace', 'the path is outside the Session working directory');
168
+ try {
169
+ const actual = await realpath(candidate);
170
+ if (!inside(rootReal, actual))
171
+ throw new HttpError(403, 'path-outside-workspace', 'the path resolves outside the Session working directory');
172
+ return actual;
173
+ }
174
+ catch (error) {
175
+ if (error instanceof HttpError)
176
+ throw error;
177
+ throw new HttpError(404, 'file-not-found', 'the requested file or directory does not exist');
178
+ }
179
+ }
180
+ function inside(root, candidate) {
181
+ const rel = relative(root, candidate);
182
+ return rel === '' || (!isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`));
183
+ }
184
+ function displayPath(root, candidate) {
185
+ return relative(root, candidate).split(sep).join('/');
186
+ }
187
+ //# sourceMappingURL=files.js.map