@nomac/sdk 1.0.0 → 1.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.
package/README.md CHANGED
@@ -63,6 +63,19 @@ For a command you follow yourself: `mac.jobs.start(command)` answers its job, `m
63
63
 
64
64
  `mac.viewLink({ control })` is a link to your user's Mac's desktop, with no NoMac sign-in, for a browser or an iframe on your site (add `?embed=1`). A watch link shows the screen; a control link takes keyboard and mouse, one controller at a time: the newest takes over and the one before watches. Two viewers per Mac at once, and watching never keeps the Mac running. Links last 2 hours by default, a day at most.
65
65
 
66
+ ### Only on your site, only for your user
67
+
68
+ ```js
69
+ import { signVisitor } from "@nomac/sdk";
70
+
71
+ const { secret } = await nomac.embed.newSecret(); // once; keep it on your server as NOMAC_EMBED_SECRET
72
+ const { url } = await mac.viewLink({ control: true, allowedOrigins: ["https://app.example.com"], visitor: user.id });
73
+ const visitor = await signVisitor({ secret: process.env.NOMAC_EMBED_SECRET, sessionId: mac.id, visitor: user.id });
74
+ // In your page: <iframe src={`${url}?embed=1#visitor=${visitor}`}>
75
+ ```
76
+
77
+ `allowedOrigins` lets only those sites frame the link, and browsers open it nowhere else. `visitor` makes it open only with your server's signature for that user, so a copied link opens nothing, in a browser or not. A signature lasts 5 minutes by default (15 at most), so sign one each time your page loads; the page then keeps working until the link expires. `nomac.embed.set({ allowedOrigins, requireVisitor })` makes both the default for every link made over the API from then on, the links in each phone's answer and those a token makes among them. Phone links take the same options.
78
+
66
79
  ### Tokens for your users
67
80
 
68
81
  `mac.token({ minutes })` is a token for that Mac only, to hand your user or their agent: `new NoMac({ token }).mac(id)` reaches its commands, files, screen, input and view links, never another Mac, a start, a stop, an extension or your account, and sees no price. It lasts 2 hours by default, a day at most, and stops when the Mac ends, when the API key that made it is revoked, or with `mac.revokeTokens()`, which ends every token and link of the Mac with the Mac running on.
@@ -0,0 +1,47 @@
1
+ import type { Transport } from "./http.ts";
2
+ import type { EmbedSettings, ViewLinkOptions } from "./types.ts";
3
+ /** A view link's request body: the options given, in NoMac's names. */
4
+ export declare function viewBody({ control, minutes, allowedOrigins, visitor }?: ViewLinkOptions): {
5
+ visitor?: string | undefined;
6
+ allowed_origins?: string[] | undefined;
7
+ minutes?: number | undefined;
8
+ control: boolean;
9
+ };
10
+ /**
11
+ * How the account's view links may be shown, for a platform that embeds its users' Macs and phones: the sites that may frame
12
+ * them, and whether each opens only for a visitor your server signed. The account's key only.
13
+ */
14
+ export declare class Embed {
15
+ #private;
16
+ constructor(http: Transport);
17
+ get(): Promise<EmbedSettings>;
18
+ /**
19
+ * Replaces both settings, for every view link made from now on (the links in each phone's answer and those a Mac's or phone's
20
+ * token makes among them): allowedOrigins ([] for any site) and requireVisitor (newSecret first). Links made before keep theirs.
21
+ */
22
+ set({ allowedOrigins, requireVisitor }: {
23
+ allowedOrigins: string[];
24
+ requireVisitor: boolean;
25
+ }): Promise<EmbedSettings>;
26
+ /**
27
+ * A new embed secret (nme_...), in this answer only: keep it on your server and sign each visitor with it (signVisitor). It
28
+ * replaces the one before at once; views already open keep working.
29
+ */
30
+ newSecret(): Promise<{
31
+ secret: string;
32
+ created_at: string;
33
+ }>;
34
+ }
35
+ /**
36
+ * Signs a visitor for a view link, on your server: an HS256 JWT (sub: the visitor, sid: the Mac's or phone's id, exp) under the
37
+ * account's embed secret. Add it to the link after #visitor= when your page shows it; the link then opens for that visitor, on
38
+ * that Mac or phone. It lasts expiresInSeconds (300 by default, 900 at most): sign a new one for each page load. Never send the
39
+ * secret to a browser.
40
+ */
41
+ export declare function signVisitor({ secret, sessionId, visitor, expiresInSeconds, now }: {
42
+ secret: string;
43
+ sessionId: string;
44
+ visitor: string;
45
+ expiresInSeconds?: number;
46
+ now?: number;
47
+ }): Promise<string>;
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Embed = void 0;
4
+ exports.viewBody = viewBody;
5
+ exports.signVisitor = signVisitor;
6
+ const errors_ts_1 = require("./errors.js");
7
+ const EMBED = "/api/v1/embed";
8
+ const encoder = new TextEncoder();
9
+ /** How long a signed visitor may last at most: NoMac refuses a longer one. */
10
+ const VISITOR_MAX_SECONDS = 15 * 60;
11
+ /** A view link's request body: the options given, in NoMac's names. */
12
+ function viewBody({ control = false, minutes, allowedOrigins, visitor } = {}) {
13
+ return { control, ...(minutes ? { minutes } : {}), ...(allowedOrigins !== undefined ? { allowed_origins: allowedOrigins } : {}), ...(visitor !== undefined ? { visitor } : {}) };
14
+ }
15
+ /**
16
+ * How the account's view links may be shown, for a platform that embeds its users' Macs and phones: the sites that may frame
17
+ * them, and whether each opens only for a visitor your server signed. The account's key only.
18
+ */
19
+ class Embed {
20
+ #http;
21
+ constructor(http) {
22
+ this.#http = http;
23
+ }
24
+ async get() {
25
+ return this.#http.request("GET", EMBED);
26
+ }
27
+ /**
28
+ * Replaces both settings, for every view link made from now on (the links in each phone's answer and those a Mac's or phone's
29
+ * token makes among them): allowedOrigins ([] for any site) and requireVisitor (newSecret first). Links made before keep theirs.
30
+ */
31
+ async set({ allowedOrigins, requireVisitor }) {
32
+ return this.#http.request("PUT", EMBED, { body: { allowed_origins: allowedOrigins, require_visitor: requireVisitor } });
33
+ }
34
+ /**
35
+ * A new embed secret (nme_...), in this answer only: keep it on your server and sign each visitor with it (signVisitor). It
36
+ * replaces the one before at once; views already open keep working.
37
+ */
38
+ async newSecret() {
39
+ return this.#http.request("POST", `${EMBED}/secret`);
40
+ }
41
+ }
42
+ exports.Embed = Embed;
43
+ const base64url = (bytes) => {
44
+ let text = "";
45
+ for (const byte of bytes)
46
+ text += String.fromCharCode(byte);
47
+ return btoa(text).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
48
+ };
49
+ /**
50
+ * Signs a visitor for a view link, on your server: an HS256 JWT (sub: the visitor, sid: the Mac's or phone's id, exp) under the
51
+ * account's embed secret. Add it to the link after #visitor= when your page shows it; the link then opens for that visitor, on
52
+ * that Mac or phone. It lasts expiresInSeconds (300 by default, 900 at most): sign a new one for each page load. Never send the
53
+ * secret to a browser.
54
+ */
55
+ async function signVisitor({ secret, sessionId, visitor, expiresInSeconds = 300, now = Date.now() }) {
56
+ if (typeof secret !== "string" || !secret.startsWith("nme_"))
57
+ throw new errors_ts_1.NoMacError("invalid_secret", "Sign with the account's embed secret (nme_...), from client.embed.newSecret(), never the API key.");
58
+ if (!/^ses_[A-Za-z0-9_-]{1,80}$/.test(sessionId))
59
+ throw new errors_ts_1.NoMacError("invalid_request", "sessionId: the Mac's or the phone's id (ses_...).");
60
+ if (!/^[A-Za-z0-9._:@-]{1,128}$/.test(visitor))
61
+ throw new errors_ts_1.NoMacError("invalid_request", "visitor: your user's id, letters, digits and . _ : @ -, up to 128.");
62
+ if (!Number.isInteger(expiresInSeconds) || expiresInSeconds < 1 || expiresInSeconds > VISITOR_MAX_SECONDS)
63
+ throw new errors_ts_1.NoMacError("invalid_request", `expiresInSeconds: a whole number from 1 to ${VISITOR_MAX_SECONDS}.`);
64
+ const issued = Math.floor(now / 1000);
65
+ const header = base64url(encoder.encode(JSON.stringify({ alg: "HS256", typ: "JWT" })));
66
+ const payload = base64url(encoder.encode(JSON.stringify({ sub: visitor, sid: sessionId, iat: issued, exp: issued + expiresInSeconds })));
67
+ const key = await crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
68
+ const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, encoder.encode(`${header}.${payload}`)));
69
+ return `${header}.${payload}.${base64url(mac)}`;
70
+ }
@@ -4,6 +4,7 @@
4
4
  * Bun, Deno, workers).
5
5
  */
6
6
  import { Labels, Webhooks } from "./account.ts";
7
+ import { Embed } from "./embed.ts";
7
8
  import { type ClientOptions, type RequestOptions } from "./http.ts";
8
9
  import { Mac, Macs } from "./mac.ts";
9
10
  import { Phone, Phones } from "./phone.ts";
@@ -18,6 +19,8 @@ export declare class NoMac {
18
19
  readonly labels: Labels;
19
20
  /** Webhooks for your users' Macs, drives and phones, and the account's credit. */
20
21
  readonly webhooks: Webhooks;
22
+ /** Where your users' view links may be shown: the sites that may frame them, and a visitor your server signs. */
23
+ readonly embed: Embed;
21
24
  /** With the account's API key (apiKey, or NOMAC_API_KEY), or with one Mac's or phone's token (token), for that one only. */
22
25
  constructor(options?: ClientOptions);
23
26
  /** A Mac by its id, without reading it: what a Mac's token reaches (new NoMac({ token }).mac(id)). */
@@ -31,6 +34,7 @@ export declare class NoMac {
31
34
  }
32
35
  export { NoMacError, requestKey } from "./errors.ts";
33
36
  export { verifyWebhook } from "./webhooks.ts";
37
+ export { Embed, signVisitor } from "./embed.ts";
34
38
  export { Mac, Macs, MacFiles, MacJobs } from "./mac.ts";
35
39
  export { Phone, Phones } from "./phone.ts";
36
40
  export { Labels, Webhooks } from "./account.ts";
package/dist/cjs/index.js CHANGED
@@ -1,12 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Webhooks = exports.Labels = exports.Phones = exports.Phone = exports.MacJobs = exports.MacFiles = exports.Macs = exports.Mac = exports.verifyWebhook = exports.requestKey = exports.NoMacError = exports.NoMac = void 0;
3
+ exports.Webhooks = exports.Labels = exports.Phones = exports.Phone = exports.MacJobs = exports.MacFiles = exports.Macs = exports.Mac = exports.signVisitor = exports.Embed = exports.verifyWebhook = exports.requestKey = exports.NoMacError = exports.NoMac = void 0;
4
4
  /**
5
5
  * NoMac from JavaScript and TypeScript: a cloud Mac or an iPhone Simulator for each of your users and agents, billed per minute,
6
6
  * over NoMac's REST API (https://nomac.app/docs/api). No dependencies; runs wherever fetch and Web Crypto do (Node 20 and later,
7
7
  * Bun, Deno, workers).
8
8
  */
9
9
  const account_ts_1 = require("./account.js");
10
+ const embed_ts_1 = require("./embed.js");
10
11
  const http_ts_1 = require("./http.js");
11
12
  const mac_ts_1 = require("./mac.js");
12
13
  const phone_ts_1 = require("./phone.js");
@@ -20,6 +21,8 @@ class NoMac {
20
21
  labels;
21
22
  /** Webhooks for your users' Macs, drives and phones, and the account's credit. */
22
23
  webhooks;
24
+ /** Where your users' view links may be shown: the sites that may frame them, and a visitor your server signs. */
25
+ embed;
23
26
  /** With the account's API key (apiKey, or NOMAC_API_KEY), or with one Mac's or phone's token (token), for that one only. */
24
27
  constructor(options = {}) {
25
28
  this.#http = new http_ts_1.Http(options);
@@ -27,6 +30,7 @@ class NoMac {
27
30
  this.phones = new phone_ts_1.Phones(this.#http);
28
31
  this.labels = new account_ts_1.Labels(this.#http);
29
32
  this.webhooks = new account_ts_1.Webhooks(this.#http);
33
+ this.embed = new embed_ts_1.Embed(this.#http);
30
34
  }
31
35
  /** A Mac by its id, without reading it: what a Mac's token reaches (new NoMac({ token }).mac(id)). */
32
36
  mac(id) {
@@ -51,6 +55,9 @@ Object.defineProperty(exports, "NoMacError", { enumerable: true, get: function (
51
55
  Object.defineProperty(exports, "requestKey", { enumerable: true, get: function () { return errors_ts_1.requestKey; } });
52
56
  var webhooks_ts_1 = require("./webhooks.js");
53
57
  Object.defineProperty(exports, "verifyWebhook", { enumerable: true, get: function () { return webhooks_ts_1.verifyWebhook; } });
58
+ var embed_ts_2 = require("./embed.js");
59
+ Object.defineProperty(exports, "Embed", { enumerable: true, get: function () { return embed_ts_2.Embed; } });
60
+ Object.defineProperty(exports, "signVisitor", { enumerable: true, get: function () { return embed_ts_2.signVisitor; } });
54
61
  var mac_ts_2 = require("./mac.js");
55
62
  Object.defineProperty(exports, "Mac", { enumerable: true, get: function () { return mac_ts_2.Mac; } });
56
63
  Object.defineProperty(exports, "Macs", { enumerable: true, get: function () { return mac_ts_2.Macs; } });
package/dist/cjs/mac.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { type Transport } from "./http.ts";
2
- import type { CommandResult, FileLink, InputAction, Job, MacSession, MacStartOptions, RunOptions, Screenshot, SessionToken, StopNotice, ViewLink } from "./types.ts";
2
+ import type { CommandResult, FileLink, InputAction, Job, MacSession, MacStartOptions, RunOptions, Screenshot, SessionToken, StopNotice, ViewLink, ViewLinkOptions } from "./types.ts";
3
3
  /** The account's Macs: start one (for one of your users with a label), read one, list them. */
4
4
  export declare class Macs {
5
5
  #private;
@@ -88,12 +88,10 @@ export declare class Mac {
88
88
  /**
89
89
  * A link to the Mac's desktop for a person, no sign-in, in a browser or an iframe (add ?embed=1): watch only, or control
90
90
  * (one controller at a time; the newest takes over). Your user's Mac only (started with a label). Lasts 2 hours by default,
91
- * a day at most; DELETE .../token (revokeTokens) ends it.
91
+ * a day at most; DELETE .../token (revokeTokens) ends it. allowedOrigins keeps it to frames on your sites, and visitor to your
92
+ * user, signed by your server (signVisitor); the account's embed settings apply when they are left out.
92
93
  */
93
- viewLink({ control, minutes }?: {
94
- control?: boolean;
95
- minutes?: number;
96
- }): Promise<ViewLink>;
94
+ viewLink(options?: ViewLinkOptions): Promise<ViewLink>;
97
95
  /**
98
96
  * A token for this Mac only, to hand your user or their agent: new NoMac({ token }).mac(id) reaches its commands, files,
99
97
  * screen, input and view links, never another Mac, a start, a stop or the account. 2 hours by default, a day at most.
package/dist/cjs/mac.js CHANGED
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MacFiles = exports.MacJobs = exports.Mac = exports.Macs = void 0;
4
4
  const errors_ts_1 = require("./errors.js");
5
+ const embed_ts_1 = require("./embed.js");
5
6
  const http_ts_1 = require("./http.js");
6
7
  const SESSIONS = "/api/v1/mac/sessions";
7
8
  const ENDED = new Set(["stopping", "stopped", "failed"]);
@@ -141,10 +142,11 @@ class Mac {
141
142
  /**
142
143
  * A link to the Mac's desktop for a person, no sign-in, in a browser or an iframe (add ?embed=1): watch only, or control
143
144
  * (one controller at a time; the newest takes over). Your user's Mac only (started with a label). Lasts 2 hours by default,
144
- * a day at most; DELETE .../token (revokeTokens) ends it.
145
+ * a day at most; DELETE .../token (revokeTokens) ends it. allowedOrigins keeps it to frames on your sites, and visitor to your
146
+ * user, signed by your server (signVisitor); the account's embed settings apply when they are left out.
145
147
  */
146
- async viewLink({ control = false, minutes } = {}) {
147
- return this.#http.request("POST", this.#path("/view"), { body: { control, ...(minutes ? { minutes } : {}) } });
148
+ async viewLink(options = {}) {
149
+ return this.#http.request("POST", this.#path("/view"), { body: (0, embed_ts_1.viewBody)(options) });
148
150
  }
149
151
  /**
150
152
  * A token for this Mac only, to hand your user or their agent: new NoMac({ token }).mac(id) reaches its commands, files,
@@ -1,5 +1,5 @@
1
1
  import { type Transport } from "./http.ts";
2
- import type { OperationOptions, PhoneLinks, PhoneRecording, PhoneSession, PhoneStartOptions, SessionToken, StopNotice, ToolName, ToolResult, ViewLink } from "./types.ts";
2
+ import type { OperationOptions, PhoneLinks, PhoneRecording, PhoneSession, PhoneStartOptions, SessionToken, StopNotice, ToolName, ToolResult, ViewLink, ViewLinkOptions } from "./types.ts";
3
3
  /** The account's phones (iPhone and iPad Simulators): start one (for one of your users with a label), read one, list them. */
4
4
  export declare class Phones {
5
5
  #private;
@@ -74,11 +74,11 @@ export declare class Phone {
74
74
  root: string;
75
75
  app?: string;
76
76
  }>;
77
- /** A link to the phone's live view for a person, no sign-in: watch only, or control: true. */
78
- viewLink({ control, minutes }?: {
79
- control?: boolean;
80
- minutes?: number;
81
- }): Promise<ViewLink>;
77
+ /**
78
+ * A link to the phone's live view for a person, no sign-in: watch only, or control: true. allowedOrigins keeps it to frames on
79
+ * your sites, and visitor to your user, signed by your server (signVisitor); the account's embed settings apply when left out.
80
+ */
81
+ viewLink(options?: ViewLinkOptions): Promise<ViewLink>;
82
82
  /** A token for this phone only, for your user or their agent: new NoMac({ token }).phone(id). 2 hours by default, a day at most. */
83
83
  token({ minutes }?: {
84
84
  minutes?: number;
package/dist/cjs/phone.js CHANGED
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Phone = exports.Phones = void 0;
4
4
  const errors_ts_1 = require("./errors.js");
5
+ const embed_ts_1 = require("./embed.js");
5
6
  const http_ts_1 = require("./http.js");
6
7
  const SESSIONS = "/api/v1/simulator/sessions";
7
8
  const ENDED = new Set(["stopping", "stopped", "failed"]);
@@ -152,9 +153,12 @@ class Phone {
152
153
  await this.#http.upload(link.upload_url, bytes);
153
154
  return this.#operation("/sync/fetch", { sha256, ...(name ? { name } : {}) }, idempotencyKey, timeoutMs);
154
155
  }
155
- /** A link to the phone's live view for a person, no sign-in: watch only, or control: true. */
156
- async viewLink({ control = false, minutes } = {}) {
157
- return this.#http.request("POST", this.#path("/view"), { body: { control, ...(minutes ? { minutes } : {}) } });
156
+ /**
157
+ * A link to the phone's live view for a person, no sign-in: watch only, or control: true. allowedOrigins keeps it to frames on
158
+ * your sites, and visitor to your user, signed by your server (signVisitor); the account's embed settings apply when left out.
159
+ */
160
+ async viewLink(options = {}) {
161
+ return this.#http.request("POST", this.#path("/view"), { body: (0, embed_ts_1.viewBody)(options) });
158
162
  }
159
163
  /** A token for this phone only, for your user or their agent: new NoMac({ token }).phone(id). 2 hours by default, a day at most. */
160
164
  async token({ minutes } = {}) {
@@ -239,10 +239,36 @@ export interface OperationOptions {
239
239
  /** How long to follow it before NoMacError "timeout" (30 minutes by default); the same key reads it later. */
240
240
  timeoutMs?: number;
241
241
  }
242
+ /** A view link; allowed_origins, visitor_required and visitor say what it is limited to, when it is. */
242
243
  export interface ViewLink {
243
244
  url: string;
244
245
  mode: "watch" | "control";
245
246
  expires_at: string;
247
+ allowed_origins?: string[];
248
+ visitor_required?: boolean;
249
+ visitor?: string;
250
+ }
251
+ export interface ViewLinkOptions {
252
+ /** The person's clicks and keys reach the Mac or phone (one at a time). Watch only by default. */
253
+ control?: boolean;
254
+ /** How long the link works: 120 by default, a day at most. */
255
+ minutes?: number;
256
+ /**
257
+ * The sites that may show the link in a frame, such as https://app.example.com, https://*.example.com or
258
+ * http://localhost:3000 (up to 10). It then opens only in a frame on one of them. The account's own list when left out.
259
+ */
260
+ allowedOrigins?: string[];
261
+ /** It opens only for this visitor (your user's id), with your server's signature from signVisitor. */
262
+ visitor?: string;
263
+ }
264
+ /** How the account's view links may be shown: they apply to every link made after they are saved. */
265
+ export interface EmbedSettings {
266
+ allowed_origins: string[];
267
+ require_visitor: boolean;
268
+ /** The embed secret's age; its value is in newSecret's answer only. */
269
+ secret: {
270
+ created_at: string;
271
+ } | null;
246
272
  }
247
273
  export interface SessionToken {
248
274
  token: string;
@@ -0,0 +1,47 @@
1
+ import type { Transport } from "./http.ts";
2
+ import type { EmbedSettings, ViewLinkOptions } from "./types.ts";
3
+ /** A view link's request body: the options given, in NoMac's names. */
4
+ export declare function viewBody({ control, minutes, allowedOrigins, visitor }?: ViewLinkOptions): {
5
+ visitor?: string | undefined;
6
+ allowed_origins?: string[] | undefined;
7
+ minutes?: number | undefined;
8
+ control: boolean;
9
+ };
10
+ /**
11
+ * How the account's view links may be shown, for a platform that embeds its users' Macs and phones: the sites that may frame
12
+ * them, and whether each opens only for a visitor your server signed. The account's key only.
13
+ */
14
+ export declare class Embed {
15
+ #private;
16
+ constructor(http: Transport);
17
+ get(): Promise<EmbedSettings>;
18
+ /**
19
+ * Replaces both settings, for every view link made from now on (the links in each phone's answer and those a Mac's or phone's
20
+ * token makes among them): allowedOrigins ([] for any site) and requireVisitor (newSecret first). Links made before keep theirs.
21
+ */
22
+ set({ allowedOrigins, requireVisitor }: {
23
+ allowedOrigins: string[];
24
+ requireVisitor: boolean;
25
+ }): Promise<EmbedSettings>;
26
+ /**
27
+ * A new embed secret (nme_...), in this answer only: keep it on your server and sign each visitor with it (signVisitor). It
28
+ * replaces the one before at once; views already open keep working.
29
+ */
30
+ newSecret(): Promise<{
31
+ secret: string;
32
+ created_at: string;
33
+ }>;
34
+ }
35
+ /**
36
+ * Signs a visitor for a view link, on your server: an HS256 JWT (sub: the visitor, sid: the Mac's or phone's id, exp) under the
37
+ * account's embed secret. Add it to the link after #visitor= when your page shows it; the link then opens for that visitor, on
38
+ * that Mac or phone. It lasts expiresInSeconds (300 by default, 900 at most): sign a new one for each page load. Never send the
39
+ * secret to a browser.
40
+ */
41
+ export declare function signVisitor({ secret, sessionId, visitor, expiresInSeconds, now }: {
42
+ secret: string;
43
+ sessionId: string;
44
+ visitor: string;
45
+ expiresInSeconds?: number;
46
+ now?: number;
47
+ }): Promise<string>;
package/dist/embed.js ADDED
@@ -0,0 +1,64 @@
1
+ import { NoMacError } from "./errors.js";
2
+ const EMBED = "/api/v1/embed";
3
+ const encoder = new TextEncoder();
4
+ /** How long a signed visitor may last at most: NoMac refuses a longer one. */
5
+ const VISITOR_MAX_SECONDS = 15 * 60;
6
+ /** A view link's request body: the options given, in NoMac's names. */
7
+ export function viewBody({ control = false, minutes, allowedOrigins, visitor } = {}) {
8
+ return { control, ...(minutes ? { minutes } : {}), ...(allowedOrigins !== undefined ? { allowed_origins: allowedOrigins } : {}), ...(visitor !== undefined ? { visitor } : {}) };
9
+ }
10
+ /**
11
+ * How the account's view links may be shown, for a platform that embeds its users' Macs and phones: the sites that may frame
12
+ * them, and whether each opens only for a visitor your server signed. The account's key only.
13
+ */
14
+ export class Embed {
15
+ #http;
16
+ constructor(http) {
17
+ this.#http = http;
18
+ }
19
+ async get() {
20
+ return this.#http.request("GET", EMBED);
21
+ }
22
+ /**
23
+ * Replaces both settings, for every view link made from now on (the links in each phone's answer and those a Mac's or phone's
24
+ * token makes among them): allowedOrigins ([] for any site) and requireVisitor (newSecret first). Links made before keep theirs.
25
+ */
26
+ async set({ allowedOrigins, requireVisitor }) {
27
+ return this.#http.request("PUT", EMBED, { body: { allowed_origins: allowedOrigins, require_visitor: requireVisitor } });
28
+ }
29
+ /**
30
+ * A new embed secret (nme_...), in this answer only: keep it on your server and sign each visitor with it (signVisitor). It
31
+ * replaces the one before at once; views already open keep working.
32
+ */
33
+ async newSecret() {
34
+ return this.#http.request("POST", `${EMBED}/secret`);
35
+ }
36
+ }
37
+ const base64url = (bytes) => {
38
+ let text = "";
39
+ for (const byte of bytes)
40
+ text += String.fromCharCode(byte);
41
+ return btoa(text).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
42
+ };
43
+ /**
44
+ * Signs a visitor for a view link, on your server: an HS256 JWT (sub: the visitor, sid: the Mac's or phone's id, exp) under the
45
+ * account's embed secret. Add it to the link after #visitor= when your page shows it; the link then opens for that visitor, on
46
+ * that Mac or phone. It lasts expiresInSeconds (300 by default, 900 at most): sign a new one for each page load. Never send the
47
+ * secret to a browser.
48
+ */
49
+ export async function signVisitor({ secret, sessionId, visitor, expiresInSeconds = 300, now = Date.now() }) {
50
+ if (typeof secret !== "string" || !secret.startsWith("nme_"))
51
+ throw new NoMacError("invalid_secret", "Sign with the account's embed secret (nme_...), from client.embed.newSecret(), never the API key.");
52
+ if (!/^ses_[A-Za-z0-9_-]{1,80}$/.test(sessionId))
53
+ throw new NoMacError("invalid_request", "sessionId: the Mac's or the phone's id (ses_...).");
54
+ if (!/^[A-Za-z0-9._:@-]{1,128}$/.test(visitor))
55
+ throw new NoMacError("invalid_request", "visitor: your user's id, letters, digits and . _ : @ -, up to 128.");
56
+ if (!Number.isInteger(expiresInSeconds) || expiresInSeconds < 1 || expiresInSeconds > VISITOR_MAX_SECONDS)
57
+ throw new NoMacError("invalid_request", `expiresInSeconds: a whole number from 1 to ${VISITOR_MAX_SECONDS}.`);
58
+ const issued = Math.floor(now / 1000);
59
+ const header = base64url(encoder.encode(JSON.stringify({ alg: "HS256", typ: "JWT" })));
60
+ const payload = base64url(encoder.encode(JSON.stringify({ sub: visitor, sid: sessionId, iat: issued, exp: issued + expiresInSeconds })));
61
+ const key = await crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
62
+ const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, encoder.encode(`${header}.${payload}`)));
63
+ return `${header}.${payload}.${base64url(mac)}`;
64
+ }
package/dist/index.d.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  * Bun, Deno, workers).
5
5
  */
6
6
  import { Labels, Webhooks } from "./account.ts";
7
+ import { Embed } from "./embed.ts";
7
8
  import { type ClientOptions, type RequestOptions } from "./http.ts";
8
9
  import { Mac, Macs } from "./mac.ts";
9
10
  import { Phone, Phones } from "./phone.ts";
@@ -18,6 +19,8 @@ export declare class NoMac {
18
19
  readonly labels: Labels;
19
20
  /** Webhooks for your users' Macs, drives and phones, and the account's credit. */
20
21
  readonly webhooks: Webhooks;
22
+ /** Where your users' view links may be shown: the sites that may frame them, and a visitor your server signs. */
23
+ readonly embed: Embed;
21
24
  /** With the account's API key (apiKey, or NOMAC_API_KEY), or with one Mac's or phone's token (token), for that one only. */
22
25
  constructor(options?: ClientOptions);
23
26
  /** A Mac by its id, without reading it: what a Mac's token reaches (new NoMac({ token }).mac(id)). */
@@ -31,6 +34,7 @@ export declare class NoMac {
31
34
  }
32
35
  export { NoMacError, requestKey } from "./errors.ts";
33
36
  export { verifyWebhook } from "./webhooks.ts";
37
+ export { Embed, signVisitor } from "./embed.ts";
34
38
  export { Mac, Macs, MacFiles, MacJobs } from "./mac.ts";
35
39
  export { Phone, Phones } from "./phone.ts";
36
40
  export { Labels, Webhooks } from "./account.ts";
package/dist/index.js CHANGED
@@ -4,6 +4,7 @@
4
4
  * Bun, Deno, workers).
5
5
  */
6
6
  import { credits, Labels, Webhooks } from "./account.js";
7
+ import { Embed } from "./embed.js";
7
8
  import { Http } from "./http.js";
8
9
  import { Mac, Macs } from "./mac.js";
9
10
  import { Phone, Phones } from "./phone.js";
@@ -17,6 +18,8 @@ export class NoMac {
17
18
  labels;
18
19
  /** Webhooks for your users' Macs, drives and phones, and the account's credit. */
19
20
  webhooks;
21
+ /** Where your users' view links may be shown: the sites that may frame them, and a visitor your server signs. */
22
+ embed;
20
23
  /** With the account's API key (apiKey, or NOMAC_API_KEY), or with one Mac's or phone's token (token), for that one only. */
21
24
  constructor(options = {}) {
22
25
  this.#http = new Http(options);
@@ -24,6 +27,7 @@ export class NoMac {
24
27
  this.phones = new Phones(this.#http);
25
28
  this.labels = new Labels(this.#http);
26
29
  this.webhooks = new Webhooks(this.#http);
30
+ this.embed = new Embed(this.#http);
27
31
  }
28
32
  /** A Mac by its id, without reading it: what a Mac's token reaches (new NoMac({ token }).mac(id)). */
29
33
  mac(id) {
@@ -44,6 +48,7 @@ export class NoMac {
44
48
  }
45
49
  export { NoMacError, requestKey } from "./errors.js";
46
50
  export { verifyWebhook } from "./webhooks.js";
51
+ export { Embed, signVisitor } from "./embed.js";
47
52
  export { Mac, Macs, MacFiles, MacJobs } from "./mac.js";
48
53
  export { Phone, Phones } from "./phone.js";
49
54
  export { Labels, Webhooks } from "./account.js";
package/dist/mac.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { type Transport } from "./http.ts";
2
- import type { CommandResult, FileLink, InputAction, Job, MacSession, MacStartOptions, RunOptions, Screenshot, SessionToken, StopNotice, ViewLink } from "./types.ts";
2
+ import type { CommandResult, FileLink, InputAction, Job, MacSession, MacStartOptions, RunOptions, Screenshot, SessionToken, StopNotice, ViewLink, ViewLinkOptions } from "./types.ts";
3
3
  /** The account's Macs: start one (for one of your users with a label), read one, list them. */
4
4
  export declare class Macs {
5
5
  #private;
@@ -88,12 +88,10 @@ export declare class Mac {
88
88
  /**
89
89
  * A link to the Mac's desktop for a person, no sign-in, in a browser or an iframe (add ?embed=1): watch only, or control
90
90
  * (one controller at a time; the newest takes over). Your user's Mac only (started with a label). Lasts 2 hours by default,
91
- * a day at most; DELETE .../token (revokeTokens) ends it.
91
+ * a day at most; DELETE .../token (revokeTokens) ends it. allowedOrigins keeps it to frames on your sites, and visitor to your
92
+ * user, signed by your server (signVisitor); the account's embed settings apply when they are left out.
92
93
  */
93
- viewLink({ control, minutes }?: {
94
- control?: boolean;
95
- minutes?: number;
96
- }): Promise<ViewLink>;
94
+ viewLink(options?: ViewLinkOptions): Promise<ViewLink>;
97
95
  /**
98
96
  * A token for this Mac only, to hand your user or their agent: new NoMac({ token }).mac(id) reaches its commands, files,
99
97
  * screen, input and view links, never another Mac, a start, a stop or the account. 2 hours by default, a day at most.
package/dist/mac.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { NoMacError, requestKey } from "./errors.js";
2
+ import { viewBody } from "./embed.js";
2
3
  import { asBytes, fromBase64, sleep, toBase64 } from "./http.js";
3
4
  const SESSIONS = "/api/v1/mac/sessions";
4
5
  const ENDED = new Set(["stopping", "stopped", "failed"]);
@@ -137,10 +138,11 @@ export class Mac {
137
138
  /**
138
139
  * A link to the Mac's desktop for a person, no sign-in, in a browser or an iframe (add ?embed=1): watch only, or control
139
140
  * (one controller at a time; the newest takes over). Your user's Mac only (started with a label). Lasts 2 hours by default,
140
- * a day at most; DELETE .../token (revokeTokens) ends it.
141
+ * a day at most; DELETE .../token (revokeTokens) ends it. allowedOrigins keeps it to frames on your sites, and visitor to your
142
+ * user, signed by your server (signVisitor); the account's embed settings apply when they are left out.
141
143
  */
142
- async viewLink({ control = false, minutes } = {}) {
143
- return this.#http.request("POST", this.#path("/view"), { body: { control, ...(minutes ? { minutes } : {}) } });
144
+ async viewLink(options = {}) {
145
+ return this.#http.request("POST", this.#path("/view"), { body: viewBody(options) });
144
146
  }
145
147
  /**
146
148
  * A token for this Mac only, to hand your user or their agent: new NoMac({ token }).mac(id) reaches its commands, files,
package/dist/phone.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { type Transport } from "./http.ts";
2
- import type { OperationOptions, PhoneLinks, PhoneRecording, PhoneSession, PhoneStartOptions, SessionToken, StopNotice, ToolName, ToolResult, ViewLink } from "./types.ts";
2
+ import type { OperationOptions, PhoneLinks, PhoneRecording, PhoneSession, PhoneStartOptions, SessionToken, StopNotice, ToolName, ToolResult, ViewLink, ViewLinkOptions } from "./types.ts";
3
3
  /** The account's phones (iPhone and iPad Simulators): start one (for one of your users with a label), read one, list them. */
4
4
  export declare class Phones {
5
5
  #private;
@@ -74,11 +74,11 @@ export declare class Phone {
74
74
  root: string;
75
75
  app?: string;
76
76
  }>;
77
- /** A link to the phone's live view for a person, no sign-in: watch only, or control: true. */
78
- viewLink({ control, minutes }?: {
79
- control?: boolean;
80
- minutes?: number;
81
- }): Promise<ViewLink>;
77
+ /**
78
+ * A link to the phone's live view for a person, no sign-in: watch only, or control: true. allowedOrigins keeps it to frames on
79
+ * your sites, and visitor to your user, signed by your server (signVisitor); the account's embed settings apply when left out.
80
+ */
81
+ viewLink(options?: ViewLinkOptions): Promise<ViewLink>;
82
82
  /** A token for this phone only, for your user or their agent: new NoMac({ token }).phone(id). 2 hours by default, a day at most. */
83
83
  token({ minutes }?: {
84
84
  minutes?: number;
package/dist/phone.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { NoMacError, requestKey } from "./errors.js";
2
+ import { viewBody } from "./embed.js";
2
3
  import { asBytes, hex, sleep } from "./http.js";
3
4
  const SESSIONS = "/api/v1/simulator/sessions";
4
5
  const ENDED = new Set(["stopping", "stopped", "failed"]);
@@ -148,9 +149,12 @@ export class Phone {
148
149
  await this.#http.upload(link.upload_url, bytes);
149
150
  return this.#operation("/sync/fetch", { sha256, ...(name ? { name } : {}) }, idempotencyKey, timeoutMs);
150
151
  }
151
- /** A link to the phone's live view for a person, no sign-in: watch only, or control: true. */
152
- async viewLink({ control = false, minutes } = {}) {
153
- return this.#http.request("POST", this.#path("/view"), { body: { control, ...(minutes ? { minutes } : {}) } });
152
+ /**
153
+ * A link to the phone's live view for a person, no sign-in: watch only, or control: true. allowedOrigins keeps it to frames on
154
+ * your sites, and visitor to your user, signed by your server (signVisitor); the account's embed settings apply when left out.
155
+ */
156
+ async viewLink(options = {}) {
157
+ return this.#http.request("POST", this.#path("/view"), { body: viewBody(options) });
154
158
  }
155
159
  /** A token for this phone only, for your user or their agent: new NoMac({ token }).phone(id). 2 hours by default, a day at most. */
156
160
  async token({ minutes } = {}) {
package/dist/types.d.ts CHANGED
@@ -239,10 +239,36 @@ export interface OperationOptions {
239
239
  /** How long to follow it before NoMacError "timeout" (30 minutes by default); the same key reads it later. */
240
240
  timeoutMs?: number;
241
241
  }
242
+ /** A view link; allowed_origins, visitor_required and visitor say what it is limited to, when it is. */
242
243
  export interface ViewLink {
243
244
  url: string;
244
245
  mode: "watch" | "control";
245
246
  expires_at: string;
247
+ allowed_origins?: string[];
248
+ visitor_required?: boolean;
249
+ visitor?: string;
250
+ }
251
+ export interface ViewLinkOptions {
252
+ /** The person's clicks and keys reach the Mac or phone (one at a time). Watch only by default. */
253
+ control?: boolean;
254
+ /** How long the link works: 120 by default, a day at most. */
255
+ minutes?: number;
256
+ /**
257
+ * The sites that may show the link in a frame, such as https://app.example.com, https://*.example.com or
258
+ * http://localhost:3000 (up to 10). It then opens only in a frame on one of them. The account's own list when left out.
259
+ */
260
+ allowedOrigins?: string[];
261
+ /** It opens only for this visitor (your user's id), with your server's signature from signVisitor. */
262
+ visitor?: string;
263
+ }
264
+ /** How the account's view links may be shown: they apply to every link made after they are saved. */
265
+ export interface EmbedSettings {
266
+ allowed_origins: string[];
267
+ require_visitor: boolean;
268
+ /** The embed secret's age; its value is in newSecret's answer only. */
269
+ secret: {
270
+ created_at: string;
271
+ } | null;
246
272
  }
247
273
  export interface SessionToken {
248
274
  token: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nomac/sdk",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "NoMac from JavaScript and TypeScript: a cloud Mac or an iPhone Simulator for each of your users and agents, billed per minute. Commands, files, screen, live desktop and phone links, per-user drives and tokens, webhooks.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://nomac.app/docs/sdks",